#include<iostream> #include<cstdio> #include<cstring> #define maxn 30010 using namespace std; int m,fa[maxn],top[maxn],num[maxn]; char s; int find(int x) { if(x==fa[x])return x; int f=fa[x]; fa[x]=find(fa[x]); num[x]=num[x]+num[f]; return fa[x]; } void merge(int a,int b) { int r1=find(a); int r2=find(b); fa[r1]=r2; find(top[r2]); num[r1]=num[top[r2]]+1; top[r2]=top[r1]; } int main() { scanf("%d",&m); int x,y; for(int i=1;i<=30000;i++) fa[i]=top[i]=i; for(int i=1;i<=m;i++) { cin>>s; if(s=='M') { scanf("%d%d",&x,&y); if(find(x)==find(y))continue; merge(x,y); } if(s=='C') { scanf("%d",&x); int tmp=find(x); printf("%d\n",num[x]); } } return 0; }
#include<iostream> #include<cstdio> #include<cstring> #define maxn 30010 using namespace std; int m,fa[maxn],top[maxn],num[maxn]; char s; int find(int x) { if(x==fa[x])return x; int f=fa[x]; fa[x]=find(fa[x]); num[x]=num[x]+num[f]; return fa[x]; } void merge(int a,int b) { int r1=find(a); int r2=find(b); fa[r1]=r2; find(top[r2]); num[r1]=num[top[r2]]+1; top[r2]=top[r1]; } int main() { //freopen("no.txt","w",stdout); scanf("%d",&m); int x,y; for(int i=1;i<=30000;i++) fa[i]=top[i]=i; for(int i=1;i<=m;i++) { cin>>s; if(s=='M') { scanf("%d%d",&x,&y); if(find(x)==find(y))continue; merge(x,y); } if(s=='C') { scanf("%d%d",&x,&y); int r1=find(x); int r2=find(y); if(r1!=r2)printf("-1\n"); else printf("%d\n",max(num[x],num[y])-min(num[x],num[y])-1); } } return 0; }