treap

写了treap..总算是过了。。

先写个递归版的非class版练练手,过几天写一个class当模板

treap=tree+heap

对于每一个,都给一个键值key,要求这个BST在保持BST性质的同时在key上也保持一个heap性质,这样就可以防止一大条链的情况

旋转和正常的差不多。。

在SPOJ3273上跑了4s+[SPOJ真TM慢。。]

#include
#include
#include
#include
#include
#include
using namespace std;

struct node{
	node *lson,*rson;
	int value,key,size;
	node(int v) :value(v),key(rand()),size(1),lson(NULL),rson(NULL){};
	void maintain(){
		if (!this) return;
		size=1;
		if (lson!=NULL) size+=lson->getsize();
		if (rson!=NULL) size+=rson->getsize();
	}
	int getsize(){
		return this?size:0;
	}
};

inline void rotate_l(node* &root){
	node* tmp=root->rson;
	root->rson=tmp->lson;
	tmp->lson=root;
	tmp->maintain();
	root->maintain();
	root=tmp;
}

inline void rotate_r(node* &root){
	node* tmp=root->lson;
	root->lson=tmp->rson;
	tmp->rson=root;
	tmp->maintain();
	root->maintain();
	root=tmp;
}

inline void forever(node* &root,const int &value){
	if (root==NULL){
		root=new node(value);
		return;
	}
	if (value==root->value) return;
	if (valuevalue){
		forever(root->lson,value);
		if (root->lson->key>root->key)
			rotate_r(root);
	}
	else{
		forever(root->rson,value);
		if (root->rson->key>root->key)
			rotate_l(root);
	}
	root->maintain();
}

inline void forget(node* &root,const int &value){
	if (root==NULL) return;
	if (value==root->value){
		if (root->lson && root->rson){
			if (root->lson->key>root->rson->key){
				rotate_r(root);
				forget(root->rson,value);
			}
			else{
				rotate_l(root);
				forget(root->lson,value);
			}
		}
		else{
			node* tmp=root;
			root=root->rson?root->rson:root->lson;
			delete tmp;
			return;
		}
	}
	else
		if (valuevalue)
			forget(root->lson,value);
		else
			forget(root->rson,value);
	root->maintain();
}

inline node* kth(node* root,int k){
	if (root==NULL) return NULL;
	int tmp=root->lson->getsize();
	if (k-1==tmp) 
		return root;
	else
		if ((k-1)lson,k);
		else
			return kth(root->rson,k-tmp-1);
}

inline int rank(node* root,const int &value){
	if (root==NULL) return 0;
	int tmp=root->lson->getsize();
	if (value==root->value)
		return tmp+1;
	else
		if (valuevalue)
			return rank(root->lson,value);
		else 
			return rank(root->rson,value)+tmp+1;
}

node *root;
int n,t;
char a,str[20];

inline void write(int k){
	if (k>root->getsize())
		printf("invalid\n");
	else
		printf("%d\n",kth(root,k)->value);
}

int main(){
	freopen("treap.in","r",stdin);
	freopen("treap.out","w",stdout);

	srand(unsigned(time));
	scanf("%d\n",&n);
	for (int i=1;i<=n;i++){
        scanf("%s%d",str,&t);
//        cout<getsize()<


你可能感兴趣的:(平衡树,2014,模板,SPOJ)