2 (Legend of Galactic Heroes) Weighted disjoint-set template

This question has 30,000 columns. . .

So right band disjoint-set on the basis of the original template must Adds an array num, num [i] represents the length of the queue i

Be up exposure. . .

code:

#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int fa[30005],val[30005],num[30005];
int find(int x)
{
    if(fa[x]!=x)
    {
        int t=fa[x];
        fa[x]=find(fa[x]);
        val[x]+=val[t]; 
    }
    return fa[x];
}
int main()
{
    int T;
    scanf("%d",&T);
    for(int i=1;i<=30000;i++)
    {
        fa[i]=i;
        num[i]=1;
    }
    char pd;
    int x,y;
    while(T--)
    {
        cin>>pd;
        scanf("%d%d",&x,&y);
        if(pd=='M')
        {
            int px=find(x);
            int py=find(y);
            if(px!=py)
            {
            fa[px]=py;
            val[px]+=num[py];
            num[py]+=num[px];
            num[px]=0;
            }
            //printf("qwq\n");
        }
        else
        if(pd=='C')
        {
            int px=find(x);
            int py=find(y);
            if(px!=py)
            {
                printf("-1\n");
            }
            else
            {
                int tmp;
                tmp=abs(val[y]-val[x]);
                printf("%d\n",tmp-1);
            }
            
        }
    }
    return 0;
    
} 

Guess you like

Origin www.cnblogs.com/ShineEternal/p/11265092.html