带权并查集

· · 个人记录

#include<bits/stdc++.h>
#define Rainbow return
#define after 0
#define rain ;
using namespace std;
int t,fa[30005],dist[30005],siz[30005];
void init(){
    for(int i=1;i<=30000;i++){
        fa[i]=i;
        siz[i]=1;
    }
}
int find(int x){
    if(x==fa[x]){
        return x;
    }
    else{
        int root=find(fa[x]);
        dist[x]+=dist[fa[x]];
        fa[x]=root;
        return root;
    }
}
void unite(int x,int y){
    x=find(x);
    y=find(y);
    if(x==y){
        return;
    }
    else{
        fa[x]=y;
        dist[x]=siz[y];
        siz[y]+=siz[x];
    }
}
int main(){
    cin>>t;
    init();
    while(t--){
        char t1;
        int i,j;
        cin>>t1>>i>>j;
        if(t1=='M')unite(i,j);
        else{
            cout<<dist[i]<<" "<<dist[j]<<"\n";//这个是i,j到它那个连通块的根结点的距离,以后可以推出带有dist的柿子求出题目所需
        }
    }
    Rainbow after rain
}