洛谷1456 Monkey King

题目:Monkey King


思路:左偏树。对于每次操作 x y ,先让x,y等于各自朋友中最大的那个,即x=find(x),y=find(y),然后再分别把x,y删除,修改权值后重新加入堆中。


代码:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <cstring>
#include <map>
using namespace std;

#define maxn 100000

int n,m;
int a[maxn+5];
int fa[maxn+5],lch[maxn+5],rch[maxn+5];
int d[maxn+5];

int merge(int x,int y) {
	if(x==0) return y;
	if(y==0) return x;
	if(a[x]<a[y]) swap(x,y);

	rch[x]=merge(rch[x],y);

	if(d[lch[x]]<d[rch[x]]) swap(lch[x],rch[x]);
	d[x]=d[rch[x]]+1;

	fa[lch[x]]=x,fa[rch[x]]=x;

	return x;
}

int find(int x) {
	if(x==fa[x]) return x;
	return find(fa[x]);
}

int chg(int x) {
	int l=lch[x],r=rch[x];
	fa[lch[x]]=lch[x],fa[rch[x]]=rch[x];
	fa[x]=x,a[x]/=2,lch[x]=rch[x]=0;
	merge(merge(l,r),x);
	return find(x);
}

int main() {

	while(~scanf("%d",&n)) {
		for(int i=1; i<=n; i++) {
			lch[i]=rch[i]=d[i]=0,fa[i]=i;
			scanf("%d",&a[i]);
		}

		scanf("%d",&m);
		for(int i=1; i<=m; i++) {
			int x,y;
			scanf("%d%d",&x,&y);
			x=find(x),y=find(y);
			if(x==y) printf("-1\n");
			else {
				x=chg(x),y=chg(y);
				merge(x,y);
				printf("%d\n",a[find(x)]);
			}
		}
	}

	return 0;
}


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值