POJ 1988 Cube Stacking

题目链接:~( ̄▽ ̄~)(~ ̄▽ ̄)~


code:

#include <stdio.h>
int father[30001], num[30001], under[30001];//father存放根节点,num存放当前这个堆有多少个方块,under[i]存放第i个方块下有几个
int find(int x)
{
	int item = father[x];//记录上回合并时x所指向的根节点
	if(x != father[x])
	{
		father[x] = find(father[x]);//更新x所指向的根节点
		under[x] += under[item]; //由于在Union中合并时x所指向的根节点的under[fx]值被更新,所以x上方的元素要加上这个值
	}
	return father[x];
}
void Union(int x, int y)
{
	int fx = find(x), fy = find(y);
	if(fx == fy)
		return;
	father[fx] = fy;
	under[fx] += num[fy];//合并时更新根节点的下方多出方块数(为y所在集合的方块数)
	num[fy] += num[fx];//记录y所在的集合有多少个正方形
}
int main()
{
	int i = 0, a = 0, b = 0, p = 0;
	char ch = 0;
	scanf("%d",&p);
	getchar();
	for(i = 1; i<30001; i++)
	{
		num[i] = 1;
		under[i] = 0;
		father[i] = i;
	}
	while(p--)
	{
		scanf("%c",&ch);
		if(ch == 'M')
		{
			scanf("%d %d",&a,&b);
			Union(a,b);
		}
		else
		{
			scanf("%d",&a);
			find(a);
			printf("%d\n",under[a]);
		}
		getchar();
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值