poj3481(treap)

注意判断指针空就用NULL,不要用!p   ~~~

ac代码:

#include<bits/stdc++.h>
using namespace std;
#define per(i,a,b) for(int i=a;i <= b;i++)
#define Max(a,b) a=max(a,b)
#define Min(a,b) a=min(a,b)
#define Sz(x) (int)x.size()
typedef long long ll;
ll gcd(ll a,ll b){while(b){ll t=b;b=a%b;a=t;} return a;}
const int inf=0x3f3f3f3f;
#define siz 37
int q,k,p;
struct TreapNode
{
    int rnd;
    TreapNode* child[2];
    int id,prior;
    TreapNode(int Kx,int Px){
        id=Kx;prior=Px;
        child[0]=child[1]=NULL;
    }
}*root,*tmp;
void Rotate(TreapNode*&u,int type)//0左旋 1右旋
{
    tmp=u->child[type^1];
    u->child[type^1]=tmp->child[type];
    tmp->child[type]=u;
    u=tmp;
}
void Insert(TreapNode*&u,int kx,int px)
{
    if(u==NULL){u=new TreapNode(kx,px);return;}
    else{
        int type=px > u->prior;
        Insert(u->child[type],kx,px);
        if(u->child[type]->prior > u->prior){
            Rotate(u,type^1);
        }
    }
}
int FindMax(TreapNode*&u)
{
    if(u==NULL)return 0;
    if(u->child[1]==NULL){//最大了
        int ans=u->id;
        tmp=u;
        u=u->child[0];
        delete tmp;
        tmp=NULL;
        return ans;
    }
    return FindMax(u->child[1]);
}
int FindMin(TreapNode*&u)
{
    if(u==NULL)return 0;
    if(u->child[0]==NULL){
        int ans=u->id;
        tmp=u;
        u=u->child[1];
        delete tmp;
        tmp=NULL;
        return ans;
    }
    return FindMin(u->child[0]);
}
void Print(TreapNode*root)
{
    if(root==NULL)return;
    Print(root->child[0]);
    printf("%d ",root->prior);
    Print(root->child[1]);
}

int main()
{
    std::ios::sync_with_stdio(false);
    root=tmp=NULL;
    while(scanf("%d",&q)!=EOF&&q!=0){
        if(q==1){
            scanf("%d %d",&k,&p);
            Insert(root,k,p);
            //if(root){printf("root : %d  ",root->prior);Print(root);printf("\n");}
        }
        else if(q==2){
            printf("%d\n",FindMax(root));
            //if(root){printf("root : %d  ",root->prior);Print(root);printf("\n");}
        }
        else if(q==3){
            printf("%d\n",FindMin(root));
            //if(root){printf("root : %d  ",root->prior);Print(root);printf("\n");}
        }
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/WindFreedom/p/9378697.html