Luogu P2342 叠积木 加权并查集
可能这是一类题目吧,这道题比较典型,可以当作模板。
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 5 const int Maxn = 30030; 6 7 int fa[Maxn],d[Maxn],size[Maxn]; 8 int find(int x){ 9 if(fa[x] == x)return x; 10 int rt = find(fa[x]); 11 d[x] += d[fa[x]]; 12 return fa[x] = rt; 13 } 14 15 void merge(int x,int y){ 16 x = find(x),y = find(y); 17 if(x != y){ 18 fa[x] = y; 19 d[x] = size[y],size[y] += size[x]; 20 } 21 } 22 23 int p,x,y; 24 char ch; 25 26 int main(){ 27 for(int i = 1;i <= 30000;i++)fa[i] = i,size[i] = 1,d[i] = 0; 28 cin >> p; 29 while(p--){ 30 cin >> ch; 31 if(ch == 'C'){ 32 cin >> x; 33 find(x); 34 cout << d[x] << '\n'; 35 } 36 else{ 37 cin >> x >> y; 38 merge(x,y); 39 } 40 } 41 return 0; 42 }