Advertisement
Josif_tepe

Untitled

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