#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=3*1e4+5;
int root[maxn],top[maxn],cnt[maxn];
int find(int num)
{
if(root[num]<0)
return num;
if(root[root[num]]>=0)
{
int fa=root[num];
root[num]=find(fa);
cnt[num]+=cnt[fa];
}
return root[num];
}
void update(int x,int y)
{
x=find(x);
y=find(y);
root[x]=y;
find(top[y]);//顺序设计非常非常巧妙,尤其是这两部,有待深思。
cnt[x]=cnt[top[y]]+1;
top[y]=top[x];
}
void init()
{
memset(root,-1,sizeof(root));
memset(cnt,0,sizeof(cnt));
for(int i=0;i<maxn;i++)
top[i]=i;
}
int main()
{
int t,x,y;
char s[5];
scanf("%d",&t);
init();
while(t--&&scanf("%s",s)!=EOF)
{
if(s[0]=='M')
{
scanf("%d%d",&x,&y);
update(x,y);
}
else
{
scanf("%d",&x);
find(x);
printf("%d\n",cnt[x]);
}
}
return 0;
}
poj 1988 并查集变形
最新推荐文章于 2022-10-21 17:31:29 发布