Advertisement
Guest User

MST

a guest
Mar 31st, 2020
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int M = 6e3+5;
  4. const int N = 1e2+5;
  5. bool visited[N];
  6. vector<pair<int, pair<int, int>>>edges;
  7.  
  8. int main ()
  9. {
  10.     int n, m;
  11.     cin >> n >> m;
  12.     int x, y, z;
  13.     for (int i = 0; i < m; i++) {
  14.         cin >> x >> y >> z;
  15.         edges.push_back({z, {x, y}});
  16.     }
  17.     sort(edges.begin(), edges.end());
  18.  
  19.     int cnt = 0;
  20.     int totalWeight = 0;
  21.     for (pair<int, pair<int, int>> i : edges) {
  22.         if (cnt == n-1)
  23.             break;
  24.         int f = i.second.first;
  25.         int s = i.second.second;
  26.         if (!visited[f] || !visited[s]) {
  27.             visited[f] = true;
  28.             visited[s] = true;
  29.             totalWeight += i.first;
  30.             cnt++;
  31.         }
  32.     }
  33.     cout << totalWeight << endl;
  34.     return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement