Advertisement
Corezzi

UVA 1160

Jan 16th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. class UF{
  7.  
  8. public:
  9.     int *a, *sz;
  10.     int n;
  11.  
  12.     UF(int n){
  13.         sz = new int[n];
  14.         a = new int[n];
  15.         this->n = n;
  16.        
  17.         for(int i =0 ; i < n; i++)
  18.             a[i] = i, sz[i] = 1;
  19.     }
  20.    
  21.     ~UF(){
  22.         delete sz;
  23.         delete a;
  24.     }
  25.    
  26.     int root(int p){
  27.         while(a[p] != p) {
  28.             a[p] = a[a[p]];
  29.             p = a[p];
  30.         }
  31.         return p;
  32.     }
  33.    
  34.     void merge(int p, int q){
  35.         int i = root(p);
  36.         int j = root(q);
  37.        
  38.         if(i == j) return;
  39.        
  40.         if(sz[i] > sz[j]) a[j] = i, sz[i] += sz[j];
  41.         else a[i] = j, sz[j] += sz[i];
  42.     }
  43.    
  44.     bool find(int p, int q){
  45.         return root(p) == root(q);
  46.     }
  47.    
  48. };
  49.  
  50. int main(){
  51.     //ios_base::sync_with_stdio(false);
  52.     //cin.tie(NULL);
  53.    
  54.     int x,y;
  55.     UF *uf = new UF(100001);
  56.     int total = 0;
  57.    
  58.     while(cin >> x){
  59.         if(x == -1){
  60.             cout << total << endl;
  61.             total = 0;
  62.             delete uf;
  63.             uf = new UF(100001);
  64.             continue;
  65.         }
  66.        
  67.         cin >> y;
  68.            
  69.         if(uf->find(x,y)) total++;
  70.         else{
  71.             uf->merge(x,y);
  72.         }  
  73.     }
  74.    
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement