Legend of the Galaxy Heroes——Niu Ke

Question link
https://ac.nowcoder.com/acm/problem/16889
idea
(if you are doing this question on AcWing, change the name of the size array to other variable names) If it is M operation, move the battleship a to b At the end of the column, then each d of the battleship a must change, that is, add size[find(b)]. Because the path is compressed, only the head needs to be changed, that is, d[find(a)]= size[find(b)].
The steps of path compression must first find the root node root, and then calculate the distance d[p[x]] from the parent node to the previous parent node, d[x] is initially the distance from x to p[x], after adding It is d[x]=d[x]+d[p[x]].
c++ code

#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;
}

Guess you like

Origin blog.csdn.net/Star_Platinum14/article/details/111952534