Advertisement
tepyotin2

Kruskal

Jun 7th, 2025
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6.  
  7. struct DSU{
  8.     vector<int> parent;
  9.     DSU(int n){
  10.         parent = vector<int>(n, -1);
  11.     }
  12.     int get(int x){
  13.         if(parent[x]<0){
  14.             return x;
  15.         }else{
  16.             return parent[x] = get(parent[x]);
  17.         }
  18.     }
  19.     bool same_set(int a, int b){
  20.         return get(a) == get(b);
  21.     };
  22.     bool unite(int x, int y){
  23.         x = get(x);
  24.         y = get(y);
  25.         if(same_set(x, y)) return false;
  26.         if(parent[x]>parent[y]){
  27.             swap(x, y);
  28.         }
  29.         parent[x]+=parent[y];
  30.         parent[y] = x;
  31.         return true;
  32.     }
  33. };
  34.  
  35. struct Path{
  36.     int a, b;
  37.     ll weight;
  38.     bool operator<(const Path &v) const{
  39.         return weight<v.weight;
  40.     }
  41. };
  42.  
  43. int n, m;
  44. vector<Path> paths;
  45. ll mst;
  46.  
  47. int main(){
  48.     //freopen("kruskal.in", "r", stdin);
  49.    
  50.     cin >> n >> m;
  51.     paths.resize(m);
  52.     for(int i=0; i<m; i++){
  53.         cin >> paths[i].a >> paths[i].b >> paths[i].weight;
  54.     }
  55.     sort(paths.begin(), paths.end());
  56.     DSU dsu(n+1);
  57.     for(int i=0; i<m; i++){
  58.         if(!dsu.same_set(paths[i].a, paths[i].b)){
  59.             dsu.unite(paths[i].a, paths[i].b);
  60.             mst+=paths[i].weight;
  61.         }
  62.     }
  63.     cout << mst << '\n';
  64.    
  65.     return 0;
  66. }
  67.  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement