BZOJ 3376 [Usaco2004 Open]Cube Stacking 方块游戏(带权并查集)
题解
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<cmath> 5 #include<algorithm> 6 using namespace std; 7 const int N=500100; 8 int q,fa[N],f[N],d[N]; 9 int find(int x){ 10 if(fa[x]!=x){ 11 int y=fa[x]; 12 fa[x]=find(y); 13 d[x]=d[y]; 14 f[x]=f[x]+f[y]; 15 } 16 return fa[x]; 17 } 18 int main(){ 19 scanf("%d",&q); 20 for(int i=1;i<=30000;i++){ 21 fa[i]=i;f[i]=0;d[i]=i; 22 } 23 char s[10]; 24 while(q--){ 25 scanf("%s",s); 26 if(s[0]=='M'){ 27 int x,y; 28 scanf("%d%d",&x,&y); 29 int a=find(x); 30 int b=find(y); 31 fa[b]=a; 32 f[b]=f[d[a]]+1; 33 d[a]=d[b]; 34 find(d[b]); 35 } 36 else{ 37 int x; 38 scanf("%d",&x); 39 find(x); 40 printf("%d\n",f[d[x]]-f[x]); 41 } 42 } 43 return 0; 44 }