Cube Stacking————Beijing University OJ

Question link
http://poj.org/problem?id=1611
Idea : The
question means that there are n bricks, numbered from 1 to n, and there are two operations, operation one ('M') is to number x Put that pile of bricks on top of the pile of bricks with number y, operation two ('C') is to query how many bricks are under the brick with number x. The traditional merge search set + maintain two arrays of size and deep. The find function needs to add the depth in sequence during the path compression process. When it is represented here, it is the maximum depth of the set. The merged process must be merged first. The number is added to the depth of merging other people's sets, and then the number is merged, and finally the merged set is cleared.
c++ code

#include<iostream>
#include<algorithm>
#include<stdio.h>
const int N =1e5+5;
using namespace std;
int deep[N];
int size[N];
int p[N];
int find(int x)
{
    
    
    if(p[x]!=x) 
    {
    
    
        int t=p[x];
        p[x]=find(p[x]);
        deep[x]+=deep[t];
    }
    return p[x];
}
void Union(int x,int y)
{
    
    
    int xx=find(x);
    int yy=find(y);
    if(xx!=yy)
    {
    
    
        p[xx]=yy;
        deep[xx]+=size[yy];
        size[yy]+=size[xx];
        size[xx]=0;
    }
}
int main()
{
    
    
	int n; 
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
    
    
        p[i]=i;
        size[i]=1;
    }
    for(int i=1;i<=n;i++)
    {
    
    
        char op[5];
        scanf("%s",op);
        if(op[0]=='M')
        {
    
    
            int a,b;
            scanf("%d %d",&a,&b);
            Union(a,b);
        }
        else if(op[0]=='C')
        {
    
    
            int a;
            scanf("%d",&a);
            find(a);
            printf("%d\n",deep[a]);
        }
    }
    return 0;
}

Guess you like

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