Advertisement
add1ctus

Градски водовод

Mar 6th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. #include <cstdio>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. int id[50001];
  8. int sz[50001];
  9.  
  10. int root(int n)
  11. {
  12. while(n != id[n])
  13. {
  14. id[n] = id[id[n]];
  15. n = id[n];
  16. }
  17. return n;
  18. }
  19.  
  20. bool check(int a, int b)
  21. {
  22. return root(a) == root(b);
  23. }
  24.  
  25. void join(int a, int b)
  26. {
  27. a = root(a);
  28. b = root(b);
  29. if(a == b)
  30. return;
  31. if(sz[a] > sz[b])
  32. {
  33. id[b] = a;
  34. sz[a] += sz[b];
  35. }
  36. else
  37. {
  38. id[a] = b;
  39. sz[b] += sz[a];
  40. }
  41. }
  42.  
  43. struct edge
  44. {
  45. int a;
  46. int b;
  47. int cost;
  48.  
  49. edge(int aa, int bb, int cc)
  50. {
  51. a = aa;
  52. b = bb;
  53. cost = cc;
  54. }
  55. };
  56.  
  57. bool operator<(const edge &lhs, const edge &rhs)
  58. {
  59. return lhs.cost < rhs.cost;
  60. }
  61.  
  62. int main()
  63. {
  64. for(int i = 0 ; i < 50001 ; ++i)
  65. {
  66. sz[i] = 1;
  67. id[i] = i;
  68. }
  69.  
  70. int n,m;
  71. scanf("%d%d",&n,&m);
  72.  
  73. // vector<pair<int,int> > graph[n];
  74. vector<edge> edges;
  75. for(int i = 0 ; i < m ; ++i)
  76. {
  77. int a,b,c,d;
  78. scanf("%d%d%d%d",&a,&b,&c,&d);
  79. int cost = c*7 + d;
  80. // graph[a].push_back(make_pair(b,cost));
  81. // graph[b].push_back(make_pair(a,cost));
  82. edges.push_back(edge(a,b,cost));
  83. }
  84.  
  85. sort(edges.begin(),edges.end());
  86.  
  87. long long result = 0;
  88.  
  89. for(int i = 0 ; i < edges.size() ; ++i)
  90. {
  91. if(!check(edges[i].a,edges[i].b))
  92. {
  93. join(edges[i].a,edges[i].b);
  94. result += edges[i].cost;
  95. }
  96. int temp = root(edges[i].a);
  97. if(sz[temp] == n)
  98. break;
  99. }
  100.  
  101. printf("%lld",result);
  102.  
  103. return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement