1. 程式人生 > >hdu 3635 帶權並查集

hdu 3635 帶權並查集

題意:

起初球i是被放在i號城市的,在年代更迭,世事變遷的情況下,球被轉移了,而且轉移的時候,連帶該城市的所有球都被移動了:T A B(A球所在的城市的所有球都被移動到了B球所在的城市),Q A(問:A球在那城市?A球所在城市有多少個球呢?A球被轉移了多少次呢?)

程式碼:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<string>
#include<map>
#include<cmath>
using namespace std;

const int maxn=10005;
int n,m;
int f[maxn],t[maxn],s[maxn];

void init(){
    memset(t,0,sizeof(t));
    for(int i=0;i<=n;++i){
        f[i]=i;
        s[i]=1;
    }
}

inline int get(int x){
    if(x==f[x]) return x;
    int p=get(f[x]);
    t[x]+=t[f[x]];
    f[x]=p;
    return p;
}

inline void join(int x,int y){
    if(x==y) return ;
    f[x]=y;
    t[x]=1;
    s[y]+=s[x];
}


int main()
{
    int T,a,b,fa,fb;
    char ch[5];
    cin>>T;
    int num=0;
    while(T--){
        scanf("%d%d",&n,&m);
        init();
        printf("Case %d:\n",++num);
        for(int i=0;i<m;++i){
            scanf("%s",ch);
            if(ch[0]=='T'){
                scanf("%d%d",&a,&b);
                fa=get(a);
                fb=get(b);
                join(fa,fb);
            }
            else{
                scanf("%d",&a);
                fa=get(a);
                printf("%d %d %d\n",fa,s[fa],t[a]);
            }
        }
    }
    return 0;
}