Advertisement
Guest User

Untitled

a guest
May 21st, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #include <cstdio>
  2. #include <queue>
  3.  
  4. using namespace std;
  5.  
  6. struct edge
  7. {
  8. int u, v;
  9. int s;
  10. };
  11.  
  12. // this is called operator overload
  13. // we can now use operator < with edges
  14. // priority_queue<edge> will also use this operator to sort edges
  15. bool operator< (edge a, edge b)
  16. {
  17. if (a.s > b.s)
  18. return true;
  19. else
  20. return false;
  21. }
  22.  
  23.  
  24. int find(int x, int* parent)
  25. {
  26. return parent[x];
  27. }
  28.  
  29. void unionx(int x, int y, int* parent, int n)
  30. {
  31. int rep_x=parent[x];
  32. int rep_y=parent[y];
  33. if(rep_x==rep_y) return;
  34. for(int i=0; i<=n; i++){
  35. if(rep_x==parent[i]){
  36. parent[i]=rep_y;
  37. }
  38. }
  39. }
  40.  
  41. unsigned long long mst(priority_queue<edge> Q, int n)
  42. {
  43. unsigned long long cost = 0;
  44. int *parent = new int[n+1];
  45.  
  46. for (int i = 0; i <= n; i++) {
  47. parent[i] = i;// ????;
  48. }
  49. for (int i = 0; i < n-1; i++) {
  50. edge e;
  51. do {
  52. e = Q.top(); Q.pop();
  53. } while (find(e.u,parent)==find(e.v,parent));
  54. cost+=e.s;
  55. unionx(e.u, e.v,parent, n);
  56. }
  57.  
  58. return cost;
  59. }
  60.  
  61. int main ()
  62. {
  63. int Z;
  64. scanf("%d", &Z);
  65. while(Z--)
  66. {
  67. int n, m;
  68. scanf ("%d %d", &n, &m);
  69.  
  70. edge temp;
  71. int u, v, s;
  72.  
  73. priority_queue<edge> Q;
  74.  
  75. for (int i = 0; i < m; i++)
  76. {
  77. scanf("%d %d %d", &u, &v, &s);
  78. edge e={u,v,s};
  79. Q.push(e);
  80. }
  81.  
  82. unsigned long long cost = mst(Q, n);
  83.  
  84. printf ("%llu\n", cost);
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement