Advertisement
Corezzi

UVA 793

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