Advertisement
Alexvans

Building Blocks

Jun 17th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <cstdio>
  2.  
  3. using namespace std;
  4.  
  5. #define N 30000
  6.  
  7. int parent[N],cont[N],top[N];
  8.  
  9. int Find(int x){
  10.     if(parent[x] != x){
  11.         int p = Find(parent[x]);
  12.         top[x] += top[ parent[x] ];
  13.         parent[x] = p;
  14.     }
  15.    
  16.     return parent[x];
  17. }
  18.  
  19. void Union(int x, int y){
  20.     x = Find(x); y = Find(y);
  21.    
  22.     if(x != y){
  23.         parent[y] = x;
  24.         top[y] = cont[x];
  25.         cont[x] += cont[y];
  26.     }
  27. }
  28.  
  29. int main(){
  30.     int P,x,y;
  31.     char s[2];
  32.    
  33.     for(int i = 0;i < N;++i){
  34.         parent[i] = i;
  35.         cont[i] = 1;
  36.         top[i] = 0;
  37.     }
  38.    
  39.     scanf("%d",&P);
  40.    
  41.     for(int p = 0;p < P;++p){
  42.         scanf("%s",s);
  43.        
  44.         if(s[0] == 'M'){
  45.             scanf("%d %d",&x,&y);
  46.             Union(x,y);
  47.         }else{
  48.             scanf("%d",&x);
  49.            
  50.             int p = Find(x);
  51.            
  52.             printf("%d\n",cont[p] - 1 - top[x]);
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement