很有技巧的并查集 参考了别人的
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int high[30005], fa[30005], top[30005], ret[30005];
void init()
{
int i;
for(i=0; i<=30000; i++)
fa[i]=i, top[i]=1, high[i]=0;
}
int find(int x)
{
int i, id=x;
for(i=0;fa[id]!=id;i++)
{
ret[i]=id;
id=fa[id];
}
for(i--;i>=0;i--)
{
high[ret[i]]+=high[fa[ret[i]]];
fa[ret[i]]=id;
}
return id;
}
int main()
{
int p, x, y, a, b;
char op[4];
while(scanf("%d",&p)!=EOF)
{
init();
while(p--)
{
scanf("%s",op);
if(op[0]=='M')
{
scanf("%d%d",&a,&b);
x=find(a), y=find(b);
if(x==y) continue;
fa[x]=y;
high[x]=top[y];
top[y]+=top[x];
}
else
{
scanf("%d",&a);
find(a);
printf("%d\n",high[a]);
}
}
}
return 0;
}