带权并查集
有蜘蛛纸牌内味。
code:
int find(int x)
{
if(father[x]==x)return x;
int fx=find(father[x]);
front[x]=front[x]+front[father[x]];
return father[x]=fx;
}
void unio(int x,int y)
{
int fx=find(x);
int fy=find(y);
father[fx]=fy;
front[fx]=behind[fy];
behind[fy]+=behind[fx];
}
void ask(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx==fy)
{
ans=abs(front[x]-front[y])-1;
printf("%d
",ans);
}
else printf("-1
");
}
void work()
{
char s;
int a,b;
for(int i=1;i<=30000;i++)
{
father[i]=i;
front[i]=0;
behind[i]=1;
}
scanf("%d
",&t);
for(int i=1;i<=t;i++)
{
scanf("%c %d%d
",&s,&a,&b);
if(s=='M')unio(a,b);
else ask(a,b);
}
}
int main()
{
work();
//while(1);
return 0;
}