HDU 3635 Dragon Balls【并查集】
题意: 有n 个城市,一开始每个城市有一颗龙珠,有 m 个操作
T a b 将a城市的所有龙珠转移到 b 城市
Q a 输出a龙珠所在的城市,和该城市现有的龙珠的数量,和该龙珠被转移的次数
分析: 并查集,x 的祖先f[x]记录x 所在城市,每次合并的时候更新路径上的点
#include<stdio.h> #include<string.h> #define maxn 10011 int city[maxn]; int move[maxn]; int f[maxn]; int find(int x) { if(f[x]==x) return x; int t=f[x]; f[x]=find(f[x]); move[x]+=move[t]; return f[x]; } void join(int x,int y) { int fx=find(x); int fy=find(y); if(fx!=fy) { city[fy]+=city[fx]; move[fx]=1; f[fx]=fy; } } int main() { char op[2]; int n,m,t,ca=1,a,b,i; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(i=1;i<=n;i++) { f[i]=i; city[i]=1; move[i]=0; } printf("Case %d:\n",ca++); while(m--) { scanf("%s",op); if(op[0]=='T') { scanf("%d%d",&a,&b); join(a,b); } else { scanf("%d",&a); int tmp=find(a); printf("%d %d %d\n",tmp,city[tmp],move[a]); } } } return 0; }