加权并查集
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include<iostream> 5 #include<algorithm> 6 #define MAXN 30005 7 #define pii pair<int,int> 8 using namespace std; 9 int p[MAXN]; 10 int f[MAXN]; 11 int r[MAXN]; 12 int t; 13 pii find(int x){ 14 if(x!=p[x]){ 15 pii t=find(p[x]); 16 p[x]=t.first; 17 f[x]+=t.second; 18 return make_pair(p[x],f[x]); 19 } 20 else{ 21 return make_pair(x,0); 22 } 23 } 24 void lik(int x,int y){ 25 pii temp; 26 temp=find(x); x=temp.first; 27 temp=find(y); y=temp.first; 28 if(x!=y){ 29 p[x]=y; 30 f[x]=r[y]+1; 31 r[y]+=(r[x]+1); 32 } 33 } 34 bool same(int x,int y){ 35 pii tempx,tempy; 36 tempx=find(x); 37 tempy=find(y); 38 return (tempx.first==tempy.first); 39 } 40 int main() 41 { 42 // freopen("data.in","r",stdin); 43 for(int i=1;i<MAXN;i++){ 44 p[i]=i; 45 } 46 scanf("%d",&t); 47 for(int i=1;i<=t;i++){ 48 char c[2]={0}; 49 int x,y; 50 scanf("%s%d%d",c,&x,&y); 51 if(c[0]=='M'){ 52 lik(x,y); 53 } 54 else{ 55 if(same(x,y)){ 56 printf("%d\n",abs(f[x]-f[y])-1); 57 } 58 else{ 59 printf("-1\n"); 60 } 61 } 62 } 63 return 0; 64 }