Question:
At first, every city had a Dragon Ball. Every t operation made all the dragon beads in the city where a Dragon Ball was located fly to the city where B Dragon Ball was located. Q operation: Which city did X Dragon Ball fly in? times
Ideas:
From the perspective of the T operation function, think of and check the set, that is, each time you find the city (find the root) to fly to another city (union)
However, when the query set fails to count the number of times each Dragon ball flew over, we can add a weight to the query set.
Make the weight of set a ++ during each flight so that when you ask X to fly several times, you only need to find the root from X and sum the weights on the path.
Code:
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define N 11000int num[N],mov[N],fa[N];int T,t,n,m;int getf(int x){ if(x!=fa[x]) { int tmp=fa[x]; fa[x]=getf(fa[x]); mov[x]+=mov[tmp]; } return fa[x];}int main(){int i,x,y,fx,fy;char op[10];while(~scanf("%d",&T)){ for(t=1;t<=T;t++) { printf("Case %d:\n",t); scanf("%d%d",&n,&m); for(i=1;i<=n;i++) { num[i]=1; fa[i]=i; mov[i]=0; } while(m--) { scanf("%s",op); if(op[0]=='T') { scanf("%d%d",&x,&y); fx=getf(x); mov[fx]++; fy=getf(y); num[fy]+=num[fx]; num[fx]=0; fa[fx]=fy; } else if(op[0]=='Q') { scanf("%d",&x); fx=getf(x); printf("%d %d %d\n",fx,num[fx],mov[x]); } } }}return 0;}
HDU 3635 dragon bils