银河英雄传说————牛客

题目链接
https://ac.nowcoder.com/acm/problem/16889
思路
(如果是在AcWing上做这题把size数组的名字改成其他变量名吧)如果是M操作即将a列战舰挪到b列的尾部,那么a列战舰的的每个d都要变,即加上size[find(b)],因为路径压缩,所以只需要头部改变即可,即d[find(a)]=size[find(b)]。
路径压缩的步骤首先要找到根节点root,然后计算父结点到上一个父结点的距离d[p[x]],d[x]初始是x到p[x]的距离,加完后是d[x]=d[x]+d[p[x]]。
c++代码

#include<bits/stdc++.h>
using namespace std;
const int N = 30005;
int p[N];
int d[N];
int size[N];
int find(int x)
{
    
    
    if(x!=p[x])
    {
    
    
        int t=find(p[x]);
        d[x]+=d[p[x]];
        p[x]=t;
    }
    return p[x];
}
int main()
{
    
    
    for(int i=0;i<N;i++)
    {
    
    
        p[i]=i;
        d[i]=0;
        size[i]=1;
    }
    int n;
    scanf("%d",&n);
    while(n--)
    {
    
    
        char op[2];
        int a,b;
        scanf("%s%d%d",op,&a,&b);
        if(op[0]=='M')
        {
    
    
            int xx=find(a);
            int yy=find(b);
            if(xx!=yy)
            {
    
    
                p[xx]=yy;
                d[xx]=size[yy];
                size[yy]+=size[xx];
            }
        }
        else if(op[0]=='C')
        {
    
    
            int aa=find(a);
            int bb=find(b);
            if(aa!=bb)
            {
    
    
                printf("-1\n");
            }
            else
            {
    
    
                printf("%d\n",max(0,abs(d[a]-d[b])-1));
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Star_Platinum14/article/details/111952534