Advertisement
tepyotin2

Base PRice

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