Advertisement
mickypinata

CUBE-T121: COI Great Raid

Mar 27th, 2020
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5. typedef long long lli;
  6.  
  7. typedef struct edge{
  8.     int u;
  9.     int v;
  10.     int w;
  11.     bool operator < (const edge &rhs)const{
  12.         return w > rhs.w;
  13.     }
  14. }edge;
  15.  
  16. priority_queue<edge> adj;
  17. vector<int> power;
  18. vector<int> parent;
  19. vector<int> ranks;
  20. int nv, ne;
  21.  
  22. void PrintPower(){
  23.     for(int i = 1; i <= nv; ++i){
  24.         cout << power[i] << " ";
  25.     }
  26.     cout << "\n";
  27.     return;
  28. }
  29.  
  30. int FindDSet(int x){
  31.     if(parent[x] == x){
  32.         return x;
  33.     } else {
  34.         return parent[x] = FindDSet(parent[x]);
  35.     }
  36. }
  37.  
  38. void UnionDSet(int f, int s){
  39.     int x = FindDSet(f);
  40.     int y = FindDSet(s);
  41.     if(ranks[x] > ranks[y]){
  42.         parent[y] = x;
  43.     } else {
  44.         parent[x] = y;
  45.         if(ranks[x] == ranks[y]){
  46.             ++ranks[y];
  47.         }
  48.     }
  49.     return;
  50. }
  51.  
  52. lli Kruskal(){
  53.     lli sum = 0;
  54.     while(!adj.empty()){
  55.         edge t = {adj.top().u, adj.top().v, adj.top().w};
  56.         adj.pop();
  57.         if(FindDSet(t.u) != FindDSet(t.v)){
  58.             sum += t.w;
  59.             UnionDSet(t.u, t.v);
  60.         }
  61.     }
  62.     return sum;
  63. }
  64.  
  65. int main(){
  66.  
  67.     int x, u, v;
  68.  
  69.     scanf("%d", &nv);
  70.     power.assign(nv + 1, 0);
  71.     parent.assign(nv + 1, 0);
  72.     ranks.assign(nv + 1, 0);
  73.     for(int i = 1; i <= nv; ++i){
  74.         scanf("%d", &x);
  75.         power[i] = x;
  76.         parent[i] = i;
  77.     }
  78.  
  79.     scanf("%d", &ne);
  80.     for(int i = 0; i < ne; ++i){
  81.         scanf("%d %d", &u, &v);
  82.         adj.push({u, v, power[u] + power[v]});
  83.     }
  84.  
  85.     cout << Kruskal();
  86.  
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement