Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <memory.h>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. struct edge {
  9. int from, to, cost;
  10.  
  11. edge(int from, int to, int cost) :
  12. from(from), to(to), cost(cost) {}
  13.  
  14. bool operator<(edge const &e) const {
  15. return cost < e.cost;
  16. }
  17. };
  18.  
  19. int n, m, to, ta, ds[40001];
  20. vector<edge> edges;
  21.  
  22. int find(int x) {
  23. return ds[x] == x ? x : ds[x] = find(ds[x]);
  24. }
  25.  
  26. int main() {
  27. while(scanf("%d %d", &n, &m) && n != 0 && m != 0) {
  28. to = ta = 0;
  29. for(int i = 0; i < n; ++i)
  30. ds[i] = i;
  31. edges.clear();
  32.  
  33. for(int i = 0, a, b, c; i < m; ++i) {
  34. scanf("%d %d %d", &a, &b, &c);
  35. edges.push_back(edge(a, b, c));
  36. }
  37. sort(edges.begin(), edges.end());
  38.  
  39. for(int i = 0, a, b; i < m && ta < n - 1; ++i) {
  40. a = find(edges[i].from);
  41. b = find(edges[i].to);
  42.  
  43. if(a != b) {
  44. ds[a] = b;
  45. to += edges[i].cost;
  46. }
  47. }
  48.  
  49. printf("%d\n", to);
  50. }
  51.  
  52. return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement