Advertisement
Corezzi

UVA 11503

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