1. 程式人生 > >ACM Treap(模板)

ACM Treap(模板)

Treap實現模板

#include <iostream>
#include <cstdlib>

using namespace std;

#define MAX_N 10000

struct Node
{
	int l,r;
	int key;
	int fix;
};

class Treap
{
	Node tree[MAX_N];
	int size;
	int root;
public:
	Treap()
	{
		root=-1;
		size=0;
		srand(time(0));
	}
	void LeftRotate(int &node)
	{
		int t=tree[node].r;
		tree[node].r=tree[t].l;
		tree[t].l=node;
		node=t;
	}
	void RightRotate(int &node)
	{
		int t=tree[node].l;
		tree[node].l=tree[t].r;
		tree[t].r=node;
		node=t;
	}
	void Insert(int &node,int key)
	{
		if(node==-1)
		{
			tree[size].l=-1;
			tree[size].r=-1;
			tree[size].fix=rand();
			tree[size].key=key;
			node=size++;
		}
		else if(tree[node].key>key)
		{
			int t=tree[node].l;
			Insert(t,key);
			if(tree[node].fix<tree[t].fix)
				RightRotate(node);
		}
		else
		{
			int t=tree[node].r;
			Insert(tree[node].r,key);
			if(tree[node].fix<tree[t].fix)
				LeftRotate(node);
		}
	}
	void Remove(int &node,int key)
	{
		if(node==-1) return;
		else if(tree[node].key>key)
			Remove(tree[node].l,key);
		else if(tree[node].key<key)
			Remove(tree[node].r,key);
		else
		{
			if(tree[node].l==-1 && tree[node].r==-1)
				node=-1;
			else if(tree[node].l==-1)
				node=tree[node].r;
			else if(tree[node].r==-1)
				node=tree[node].l;
			else if(tree[tree[node].l].fix>tree[tree[node].r].fix)
			{
				RightRotate(node);
				Remove(tree[node].r,key);
			}
			else
			{
				LeftRotate(node);
				Remove(tree[node].l,key);
			}
		}
	}
	bool Find(int root,int key)
	{
		if(root==-1)
			return false;
		else if(tree[root].key<key)
			return Find(tree[root].r,key);
		else if(tree[root].key>key)
			return Find(tree[root].l,key);
		else
			return true;
	}
	bool Find(int key)
	{
		return Find(root,key);
	}
	void Insert(int key)
	{
		Insert(root,key);
	}
	void Remove(int key)
	{
		Remove(root,key);
	}
};

Treap treap;

int main()
{
	treap.Insert(1);

	cout<<treap.Find(1)<<endl;
	treap.Remove(1);
	cout<<treap.Find(1)<<endl;

	return 0;
}