hdu2818 Building Block

//并查集好题,对并查集有了深入的理解
#include <stdio.h>

int father[30005];
int num[30005];
int lownum[30005];//树某节点下面的节点数

int find(int x)
{
	int temp;
	if(x==father[x])
		return x;
	temp=find(father[x]);
	lownum[x]+=lownum[father[x]];	
	return father[x]=temp;
}

void init()
{
	int i;
	for(i=0;i<=30002;i++)
	{
		father[i]=i;
		num[i]=1;
		lownum[i]=0;
	}
}

int main()
{
	int p,x,y,fx,fy;
	char ch;
	init();
	scanf("%d",&p);
	while(p--)
	{
		getchar();
		scanf("%c",&ch);
		if(ch=='M')
		{
			scanf("%d %d",&x,&y);
			fx=find(x);
			fy=find(y);
			if(fx!=fy)
			{
				father[fx]=fy;
				lownum[fx]=num[fy];
				num[fy]+=num[fx];
			}
			else
				continue;
		}
		else
		{
			scanf("%d",&x);
			find(x);
			printf("%d\n",lownum[x]);
		}
	}
	return 0;
}

你可能感兴趣的:(hdu2818 Building Block)