N - Building Block HDU - 2818(带权并查集)

John are playing with blocks. There are N blocks (1 <= N <= 30000) numbered 1…N。Initially, there are N piles, and each pile contains one block. Then John do some operations P times (1 <= P <= 1000000). There are two kinds of operation:

M X Y : Put the whole pile containing block X up to the pile containing Y. If X and Y are in the same pile, just ignore this command.

C X : Count the number of blocks under block X

You are request to find out the output for each C operation.

Input
The first line contains integer P. Then P lines follow, each of which contain an operation describe above.

Output
Output the count for each C operations in one line.

Sample Input
6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4

Sample Output
1
0
2

题意:
输入M时,要输入两个数,并把包含前一个数的树整体放在包含后一个数的树上,求树中某个数下方有几个数。
样例演示:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

AC代码:

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<map>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
int pre[30005];
int d[30005];//记录树上每个点的深度 
int r[30005];//记录树的高度(根节点的高度) 
void make()
{
	for(int i=0;i<30005;i++)
	{
		pre[i]=i;
		d[i]=0;//深度为0
		r[i]=1;//初始为1(本身)
	}
}
int find(int i)
{
	int fx;
	if(pre[i]==i)
	{
		return i;
	}
	fx=pre[i];//记录更新前指向的位置(压缩路径后返回的值是根节点,提前记录::本人不熟悉递归,被坑一次)
	pre[i]=find(fx);//压缩路径 
	d[i]+=d[fx];//递归依次更新树上每个点的深度 
	return pre[i];//压缩路径 
}
void unite(int i,int j)
{
	int x=find(i);
	int y=find(j);
	if(y==x)
	{
		return ;
	}
	pre[x]=y;//合并两棵树 
	d[x]=r[y];//更新树的深度 
	r[y]+=r[x];//更新树的高度
	return ;
}
int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		make();
		for(int i=0;i<n;i++)
		{
			char ss;
			cin>>ss;
			if(ss=='M')
			{
				int x,y;
				scanf("%d %d",&x,&y);
				unite(x,y);
			}
			else
			{
				int x;
				scanf("%d",&x);
				find(x);//调用find()把含x树更新一遍 
				printf("%d\n",d[x]);
			}
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值