1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include<cstdio> #include<iostream> #include<algorithm> #include<cstring> using namespace std; int t; int q[99999]; int h[99999]; int f[99999]; int find(int x) { if(f[x]==x)return x; int fx=find(f[x]); q[x]=q[x]+q[f[x]]; return f[x]=fx; //if(f[x]!=x) f[x]=find(f[x]); // q[x]=q[x]+q[f[x]]; //return f[x]; } void work(int b,int c) { int fx=find(b); int fy=find(c); //q[fx]=fy; q[fx]=h[fy]; h[fy]+=h[fx]; //q[c]=q[b]+h[b]+q[c]; //h[b]=h[b]+h[c]; f[fx]=fy; } int main() { scanf("%d",&t); for(int i=1;i<=30000;i++) f[i]=i,h[i]=1; for(int i=1;i<=t;i++) { char a; int b,c; cin>>a>>b>>c; if(a=='M') { work(b,c); } if(a=='C') { if(find(b)==find(c)) printf("%d\n",abs(q[b]-q[c])-1); else printf("-1\n"); } } return 0; }
|