Advertisement
Josif_tepe

Untitled

Apr 7th, 2024
574
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5. using namespace std;
  6. const int maxn = 1e5 + 10;
  7. const int INF = 2e9;
  8. int n, m;
  9. vector<pair<int, pair<int, int>>> graph;
  10. int idx[maxn], sz[maxn];
  11. int root(int x) {
  12.     while(x != idx[x]) {
  13.         idx[x] = idx[idx[x]];
  14.         x = idx[x];
  15.     }
  16.     return x;
  17. }
  18. void join(int a, int b) {
  19.     int root_a = root(a), root_b = root(b);
  20.     if(root_a != root_b) {
  21.         if(sz[root_a] < sz[root_b]) {
  22.             sz[root_b] += sz[root_a];
  23.             idx[root_a] = idx[root_b];
  24.         }
  25.         else {
  26.             sz[root_a] += sz[root_b];
  27.             idx[root_b] = idx[root_a];
  28.         }
  29.     }
  30. }
  31. int main() {
  32.     cin >> n >> m;
  33.     for(int i = 1; i <= n; i++) {
  34.         sz[i] = 1;
  35.         idx[i] = i;
  36.     }
  37.     for(int i = 0; i < m; i++) {
  38.         int a, b, c;
  39.         cin >> a >> b >> c;
  40.         graph.push_back(make_pair(c, make_pair(a, b)));
  41.     }
  42.     sort(graph.begin(), graph.end());
  43.    
  44.     int mst = 0;
  45.     for(int i = 0; i < m; i++) {
  46.         int a = graph[i].second.first;
  47.         int b = graph[i].second.second;
  48.         int c = graph[i].first;
  49.        
  50.         if(root(a) != root(b)) {
  51.             join(a, b);
  52.             mst += c;
  53.         }
  54.     }
  55.     cout << mst << endl;
  56.     return 0;
  57. }
  58. /*
  59.  6 9
  60.  5 4 9
  61.  5 1 4
  62.  1 4 1
  63.  1 2 2
  64.  2 4 3
  65.  2 3 3
  66.  2 6 7
  67.  3 6 8
  68.  4 3 5
  69.  
  70.  **/
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement