hdu 3635(并查集的应用)

路径压缩的时候维护移动次数

合并的时候更新每个城市的龙珠数量

这题要理解并查集路径压缩

#include
#include
const int maxn = 10005;
int n,q;
char op[5];
struct node
{
    int par;
    int son;
    int step;
}ball[maxn];
int find(int x)
{
    if(x==ball[x].par) return x;
    int temp = ball[x].par;
    ball[x].par = find(ball[x].par);
    ball[x].step += ball[temp].step;
    return ball[x].par;
}
int main()
{
    int cases,a,b,t=1;
    scanf("%d",&cases);
    while(cases--)
    {
        scanf("%d%d",&n,&q);
        for(int i=0;i<=n;i++)
        {
            ball[i].par = i;
            ball[i].son = 1;
            ball[i].step = 0;
        }
        printf("Case %d:\n",t++);
        while(q--)
        {
           scanf("%s",op);
           if(op[0]=='T')
           {
               scanf("%d%d",&a,&b);
               int k1 = find(a);
               int k2 = find(b);
               if(k1!=k2)
               {
                   ball[k1].par = k2;
                   ball[k1].step++;
                   ball[k2].son += ball[k1].son;
                   ball[k1].son = 0;
               }
           }
           else
           {
               scanf("%d",&a);
               int k = find(a);
               printf("%d ",k);
               printf("%d ", ball[k].son);
               printf("%d\n",ball[a].step);
           }
        }
    }
    return 0;
}


你可能感兴趣的:(并查集)