洛谷 P1456 Monkey King(左偏树)

左偏树
本题要点:
1、首先,每一个节点里需要加入指向父节点的下标 fa。
2、这里的左偏树根节点是最大元素, merge 函数里面,

if(tree[x].val < tree[y].val)	// 根节点是最大元素,这里是小于号
	swap(x, y);

3、然后每一查找到 点x所在的左偏树的根节点 fax, fax 的 val 减半, 这时候需要调整 fax 的位置:
先合并 fax 的左右孩子 merge(tree[fax].lc, tree[fay].rc) (假设为newtree),
在合并 fax 和 newtree, merge(fax, newtree)
4、对于每一次查询,x, y, 找到其根节点 fax, fay
如果 fax == fay, 输出 -1
否则, 两棵树根先减半,调整后,再合并这两棵树,输出合并后的树的根 的 val 值。

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MaxN = 100010;
int n, m;

struct node
{
	int val, lc, rc, dis, fa;	//val表示值,lc合rc分别表示左子树合右子树,dis表示节点的距离,fa表示父亲
}tree[MaxN];

int merge(int x, int y)
{
	if(0 == x)	return y;
	if(0 == y)	return x;
	if(tree[x].val < tree[y].val)	// 根节点是最大元素,这里是小于号
		swap(x, y);
	tree[x].rc = merge(tree[x].rc, y);
	tree[tree[x].rc].fa = x;
	if(tree[tree[x].rc].dis > tree[tree[x].lc].dis)
	{
		swap(tree[x].rc, tree[x].lc);
	}
	if(tree[x].rc == 0)	
	{
		tree[x].dis = 0;	
	}else{
		tree[x].dis = tree[tree[x].rc].dis + 1;
	}
	return x;
}

int get(int x)
{
	if(x == tree[x].fa)
		return x;
	return get(tree[x].fa);
}

//调整根节点
int adjust(int x)
{
	int l = tree[x].lc, r = tree[x].rc;
	tree[x].lc = tree[x].rc = tree[x].dis = 0;
	tree[x].val /= 2, tree[x].fa = x;
	tree[l].fa = l, tree[r].fa = r;
	return merge(x,  merge(l, r));
}

int main()
{
	int x, y;
	while(scanf("%d", &n) != EOF)
	{
		for(int i = 1; i <= n; ++i)
		{
			scanf("%d", &tree[i].val);
			tree[i].lc = tree[i].rc = 0, tree[i].fa = i;
		}
		scanf("%d", &m);
		for(int i = 0; i < m; ++i)
		{
			scanf("%d%d", &x, &y);
			int fax = get(x), fay = get(y);
			if(fax == fay)
			{
				printf("-1\n");	
			}else{
				int fa = merge(adjust(fax), adjust(fay));
	//			printf("fax = %d, fay = %d, fa = %d\n", fa, fax, fay);
				printf("%d\n", tree[fa].val);
			}
		}
	}
	return 0;
}

/*
5
20
16
10
10
4
5
2 3
3 4
3 5
4 5
1 5
*/

/*
8
5
5
-1
10
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值