罗马游戏[可并堆]

本文介绍了一种使用大根堆和并查集的数据结构解决方案,用于处理动态集合的合并与删除操作。通过避免路径压缩,确保了每个点所在集合的根节点随操作动态变化。代码示例展示了如何在C++中实现这一算法,包括随机化平衡树的合并、查找和删除功能。

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

传送门

写一个大根堆就可以了 , 注意并查集找fa不能路径压缩 , 因为每个点所在的集合的根是变化的


#include<bits/stdc++.h>
#define N 1000050
using namespace std;
struct Node{int l,r;}t[N];
int n,m,a[N],fa[N],killed[N]; char s[10];
int read(){
	int cnt=0;char ch=0;
	while(!isdigit(ch))ch=getchar();
	while(isdigit(ch))cnt=cnt*10+(ch-'0'),ch=getchar();
	return cnt; 
} 
int find(int x){return x==fa[x]?x:find(fa[x]);}
int Merge(int x,int y){
	if(!x || !y) return x+y;
	if(a[x] > a[y]) swap(x,y);
	t[x].l = Merge(t[x].l , y); 
	fa[t[x].l] = x;
	if(rand()%2) swap(t[x].l , t[x].r);
	return x;
}
void Delete(int x){
	killed[x]=1;
	fa[t[x].l] = t[x].l;
	fa[t[x].r] = t[x].r;
	Merge(t[x].l , t[x].r);
}
void Kill(int x){
	if(killed[x]){printf("0\n"); return;}
	x=find(x); printf("%d\n",a[x]); Delete(x);
}
int main(){
	srand(time(0));
	n=read();
	for(int i=1;i<=n;i++) a[i]=read() , fa[i]=i;
	m=read(); while(m--){
		scanf("%s",s); 
		if(s[0]=='K') Kill(read());
		if(s[0]=='M'){
			int x=read(),y=read(); 
			if(killed[x] || killed[y]) continue;
			x=find(x),y=find(y);
			if(x != y) Merge(x,y);
		}
	}return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FSYo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值