Advertisement
mickypinata

TOI11: Sacred Places

Apr 22nd, 2020
836
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <tuple>
  5. using namespace std;
  6.  
  7. #define lli long long
  8. #define tiii tuple<int, int, int>
  9.  
  10. priority_queue<tiii> q; /// (w, u, v)
  11. vector<int> DS;
  12. vector<int> ranks;
  13. int nv, ne;
  14.  
  15. int DSFind(int x){
  16.     if(DS[x] == x){
  17.         return x;
  18.     } else {
  19.         return DS[x] = DSFind(DS[x]);
  20.     }
  21. }
  22.  
  23. void DSUnion(int x, int y){
  24.     int fx = DSFind(x);
  25.     int fy = DSFind(y);
  26.     if(ranks[fx] > ranks[fy]){
  27.         DS[fy] = fx;
  28.     } else {
  29.         DS[fx] = fy;
  30.         if(ranks[fx] == ranks[fy]){
  31.             ++ranks[fy];
  32.         }
  33.     }
  34.     return;
  35. }
  36.  
  37. lli KruskalMaxST(){
  38.     lli cnt = 0;
  39.     while(!q.empty()){
  40.         int w = get<0>(q.top());
  41.         int u = get<1>(q.top());
  42.         int v = get<2>(q.top());
  43.         q.pop();
  44.         if(DSFind(u) != DSFind(v)){
  45.             DSUnion(u, v);
  46.             cnt += w - 1;
  47.         }
  48.     }
  49.     return cnt;
  50. }
  51.  
  52. int main(){
  53.  
  54.     int u, v, w;
  55.  
  56.     scanf("%d %d", &nv, &ne);
  57.     DS.assign(nv + 1, 0);
  58.     ranks.assign(nv + 1, 1);
  59.     for(int i = 1; i <= nv; ++i){
  60.         DS[i] = i;
  61.     }
  62.  
  63.     for(int i = 0; i < ne; ++i){
  64.         scanf("%d %d %d", &u, &v, &w);
  65.         q.emplace(w, u, v);
  66.     }
  67.  
  68.     cout << KruskalMaxST();
  69.  
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement