HDU【1512】Monkey King(左偏堆)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1512
分析
这道题需要合并两个集合,因此可以想到并查集,又需要找到集合中的最大值,可以想到大根堆,问题转化为把两个大根堆合并,所以可以推出左偏堆,一种可并堆。注意题目中的认识具有传递性。

#include<iostream>
#include<cstdio>
using namespace std;
const int N = 1e5 + 10;
struct Node {
	int l,r,key,dis;
} heap[N];
int n,m,f[N];
int find(int x)
{
	if(x == f[x]) return x;
	return f[x] = find(f[x]);
}
int merge(int x,int y)
{
	if(!x || !y) return x | y;
	if(heap[x].key < heap[y].key) swap(x,y);//找到两个堆中键值较大的(大根堆),反过来就是小根堆
	heap[x].r = merge(heap[x].r,y);
	f[heap[x].r] = x;
	if(heap[heap[x].l].dis < heap[heap[x].r].dis) swap(heap[x].l,heap[x].r);//任意节点的左子节点的距离不小于右子节点的距离
	if(heap[x].r == 0) heap[x].dis = 0;//如果节点x没有右子节点,则距离为0
	else heap[x].dis = heap[heap[x].r].dis + 1;//节点x的距离等于右子节点的距离+1
	return x;
}
int pop(int x)
{
	int l = heap[x].l,r = heap[x].r;
	f[l] = l,f[r] = r;
	heap[x].l = heap[x].r = heap[x].dis = 0;
	return merge(l,r);
}
int main()
{
	while(~scanf("%d",&n)) {
		for(int i = 1; i <= n; i++) {
			scanf("%d",&heap[i].key);
			heap[i].l = heap[i].r = heap[i].dis = 0;
			f[i] = i;
		}
		int u,v;
		scanf("%d",&m);
		for(int i = 0; i < m; i++) {
			scanf("%d%d",&u,&v);
			u = find(u),v = find(v);//找到集合中key最大的点
			if(u == v) printf("-1\n");//如果两个人认识
			else {
				heap[u].key /= 2;
				heap[v].key /= 2;
				int l = pop(u),r = pop(v);
				l = merge(l,u);
				r = merge(r,v);
				l = merge(l,r);
				printf("%d\n",heap[l].key);
			}
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值