hdu 2818 Building Block 并查集 路径压缩

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 30005
int set[N];
int num[N];
int cnt[N];

int find(int x){
	if(set[x]==x) return x;
	int temp=set[x];
	set[x]=find(set[x]);//路径压缩,不进行路径压缩果断的超时!!
	cnt[x]+=cnt[temp];//合并结果
	return set[x];
}
void insert(int x,int y){
	int fx=find(x);
	int fy=find(y);
	if(fx==fy) return;
	cnt[fx]=num[fy];
	num[fy]+=num[fx];
	num[fx]=0;
	set[fx]=fy;//通过这里将两个集合合并了
}
int main(){
	int n;
	while(scanf("%d",&n)!=EOF){
		for(int i=0;i<N;i++){
			set[i]=i;
			num[i]=1;//包含数字i的那个pile上总共有多少个数字
			cnt[i]=0;//当前数字下面的数量
		}
		int x,y;
		char ch;
		while(n--){
			getchar();//吸收换行
			scanf("%c",&ch);
			if(ch=='M'){
				scanf("%d%d",&x,&y);
				insert(x,y);
			}
			else {
				scanf("%d",&x);
				find(x);
				printf("%d\n",cnt[x]);
			}
		}
	}
	return 0;
}
刚开始时用的是队列模拟,果断的超时,在合并的时候更新了当前队列里的所有值,其实这不需要,查找的时候再更新就行了,还有就是通过路径压缩可以很快找到当前点所属的集合,对于这题如果不进行压缩就会超时。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值