左偏树 Leftist Tree

see: http://acm.sdut.edu.cn/bbs/read.php?tid=1177 黄源河:《左偏树的特点及其应用》

1. 定义:

左偏树(Leftist Tree)是一种可并堆的实现。左偏树是一棵二叉树,它的节点除了和二叉树的节点一样具有左右子树指针( left, right )外,还有两个属性:键值和距离(dist)。键值上面已经说过,是用于比较节点的大小。距离则是如下定义的:
节点i称为外节点(external node),当且仅当节点i的左子树或右子树为空 ( left(i) = NULL或right(i) = NULL );节点i的距离(dist(i))是节点i到它的后代中,最近的外节点所经过的边数。特别的,如果节点i本身是外节点,则它的距离为0;而空节点的距离规定为-1 (dist(NULL) = -1)。在本文中,有时也提到一棵左偏树的距离,这指的是该树根节点的距离。

2. 优点:

合并复杂度 O(log N)

最小堆的合并复杂度为O(N).

3. 代码:

#include <cstdio>
#include <algorithm>
using namespace std;

#define typec int

const int na = -1;

const int N = 1000;

struct node
{
	typec key;
	int l, r, f, dist;
}tr[N];

// find i's root
int iroot(int i)
{
	if(i == na)
	{
		return i;
	}
	while(tr[i].f != na) 
	{
		i = tr[i].f;
	}
	return i;
}

// two root: rx, ry
int merge(int rx, int ry)
{
	if(rx == na)
	{
		return ry;
	}

	if(ry == na)
	{
		return rx;
	}

	if(tr[rx].key > tr[ry].key)
	{
		swap(rx, ry);
	}

	int r = merge(tr[rx].r, ry);

	tr[rx].r = r;
	tr[r].f = rx;

	if(tr[r].dist > tr[tr[rx].l].dist)
	{
		swap(tr[rx].l, tr[rx].r);
	}

	if(tr[rx].r == na)
	{
		tr[rx].dist = 0;
	}
	else
	{
		tr[rx].dist = tr[tr[rx].r].dist + 1;
	}
	return rx;
}

// add a new node (i, key)
int ins(int i, typec key, int root)
{
	tr[i].key = key;
	tr[i].l = tr[i].r = tr[i].f = na;
	tr[i].dist = 0;
	return root = merge(root, i);
}

// delete node i
int del(int i)
{
	if(i == na)
	{
		return i;
	}

	int x, y, l, r;

	l = tr[i].l;
	r = tr[i].r;
	y = tr[i].f;

	tr[i].l = tr[i].r = tr[i].f = na;

	tr[x=merge(l,r)].f = y;

	if(y != na && tr[y].l == i)
	{
		tr[y].l = x;	
	}

	if(y != na && tr[y].r == i)
	{
		tr[y].r = x;	
	}

	for(; y != na; x = y, y = tr[y].f)
	{
		if(tr[tr[y].l].dist < tr[tr[y].r].dist)
		{
			swap(tr[y].l, tr[y].r);
		}
		if(tr[tr[y].r].dist + 1 == tr[y].dist)
		{
			break;
		}
		tr[y].dist = tr[tr[y].r].dist + 1;
	}

	if(x != na)
	{
		return iroot(x);
	}
	else
	{
		return iroot(y);
	}
}

node top(int root)
{
	return tr[root];
}

node pop(int &root)
{
	node out = tr[root];
	int l = tr[root].l, r = tr[root].r;
	tr[root].l = tr[root].r = tr[root].f = na;
	tr[l].f = tr[r].f = na;
	root = merge(l, r);
	return out;
}

int add(int i, typec val)
{
	if(i == na)
	{
		return i;
	}

	if(tr[i].l == na && tr[i].r == na && tr[i].f == na)
	{
		tr[i].key += val;
		return i;
	}

	typec key = tr[i].key + val;
	int rt = del(i);
	return ins(i, key, rt);
}

void init(int n)
{
	for(int i = 1; i < N; i++)
	{
		scanf("%d", &tr[i].key);
		tr[i].l = tr[i].r = tr[i].f = na;
		tr[i].dist = 0;
	}
}

// print the info of node i
void print(int i)
{
	printf("node %d : l-> %d, r-> %d, f-> %d, dist-> %d\n", i, tr[i].l, tr[i].r, tr[i].f, tr[i].dist);
}

int main()
{
	int root = na;
	for(int i = 1; i < 16; i++)
	{
		root = ins(i, i, root);
	}
	for(int i = 1; i < 16; i++)
	{
		print(i);
	}
	del(1);
	for(int i = 1; i < 16; i++)
	{
		print(i);
	}

	return 0;
}

你可能感兴趣的:(struct,tree,null,delete,merge)