POJ 1988 Cube Stacking

本文介绍了一个使用并查集解决木块堆叠问题的具体案例。通过定义数据结构和实现并查集的基本操作,如查找根节点和合并集合,来跟踪木块堆叠的状态。文章中的代码实现了输入命令来动态更新木块堆叠情况,并输出指定木块下方的木块数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址

total[x]记录最下方木块是x,这一堆总共有多少木块

under[x]记录x木块下面有几块木块

#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<cctype>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=30000 + 5;
int Par[maxn],total[maxn],under[maxn];
int getPar(int x){
	if(Par[x]==x) return x;
	int p=getPar(Par[x]);
	under[x]+=under[Par[x]];  //加上到那一堆之前的所有根节点 
	Par[x]=p;
	return p; 
}
void merge(int a,int b){
	int p1=getPar(a);
	int p2=getPar(b);
	if(p1==p2) return ;
	Par[p2]=p1;
	under[p2]=total[p1];
	total[p1]+=total[p2];
}
int main()
{
	int N;
	cin>>N;
	for(int i=1;i<maxn;i++){
		total[i]=1;
		under[i]=0;
		Par[i]=i;
	}
	string cmd;
	while(N--)
	{
		cin>>cmd;
		if(cmd[0]=='M') {
			int x,y; cin>>x>>y;
			merge(y,x);
		}
		else {
			int x; cin>>x;
			getPar(x);
			cout<<under[x]<<endl;
		}
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值