Treap模板

来源:互联网 发布:高清混合矩阵排名 编辑:程序博客网 时间:2024/05/29 18:28

Treap,又称树堆,是一个随机附加域满足堆性质的二叉搜索树,其结构相当于随机数据插入的二叉搜索树。其基本的期望时间复杂度为O(logn)。相对于其他的平衡二叉搜索树,Treap的特点是实现简单,且能基本实现随机平衡结构。
Treap的作用是:它的作用同BST一样,引入优先级的概念是为了防止BST退化成一个链表,其他的查找复杂度为O(n),当然可以完全随机的插入节点,但是有时候并不知道所有的节点,这种情况下可以采用Treap,即当需要插入一个新的key的值时,可以随机的生成一个优先级(fix)约束Treap,从而达到随机生成BST 的目的。

#include<cstdio>#include <cstring>#include <cstdlib>#include <time.h>#include <iostream>using namespace std;struct Treap_Node{    Treap_Node *left,*right;    int val,fix;//关键值,随机优先值};void Treap_Left_Rotate(Treap_Node * &a){    Treap_Node *b=a->right;    a->right=b->left;    b->left=a;    a=b;}void Treap_Right_Rotate(Treap_Node *&a){    Treap_Node * b=a->left;    a->left=b->right;    b->right=a;    a=b;}void Treap_Insert(Treap_Node *&p,int val){    if(!p)    {        p=(Treap_Node*)malloc(sizeof (Treap_Node));        if(p==NULL)            exit(1);        p->val=val;        p->fix=rand();        p->left=p->right=NULL;    }    else if(val<=p->val)    {        Treap_Insert(p->left,val);        if(p->left->fix<p->fix)            Treap_Right_Rotate(p);    }    else    {        Treap_Insert(p->right,val);        if(p->right->fix<p->fix)            Treap_Left_Rotate(p);    }}void Treap_Delete(Treap_Node *&p,int val){    if(val==p->val)    {        Treap_Node *t=p;        if(!p->right)        {            p=p->left;            delete t;        }        else if(!p->left)        {            p=p->right;             delete t;        }        else        {            if(p->left->fix<p->right->fix)            {                Treap_Right_Rotate(p);                Treap_Delete(p->right,val);            }            else            {                Treap_Left_Rotate(p);                Treap_Delete(p->left,val);            }        }    }    else if(val<p->val)        Treap_Delete(p->left,val);    else        Treap_Delete(p->right,val);}void PrintTree(Treap_Node *p){    if(p)    {        PrintTree(p->left);        printf("%d %d\n",p->val,p->fix);        PrintTree(p->right);    }}int main(){    Treap_Node *root=NULL;    srand((unsigned int)time(NULL));    for(int i=0; i<100; i++)    {        Treap_Insert(root,i);    }    cout<<"Print tree"<<endl;    PrintTree(root);    for(int i=0; i<100; i++)    {        Treap_Delete(root,i);    }    cout<<"Print Tree After Delete:"<<endl;    PrintTree(root);    return 0;}