[NOI2002]银河英雄传说

带权并查集

有蜘蛛纸牌内味。

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\n",ans);
     }
     else printf("-1\n");
}
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\n",&t);
     for(int i=1;i<=t;i++)
     {
         scanf("%c %d%d\n",&s,&a,&b);
         if(s=='M')unio(a,b);
         else ask(a,b);
     }
}
int main()
{
    work();
    //while(1);
    return 0;
}
posted @ 2020-11-22 18:55  GUO_dx  阅读(68)  评论(0编辑  收藏  举报