左偏树
本题要点:
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
*/