hdu1908

来源:互联网 发布:中国出境旅游数据 编辑:程序博客网 时间:2024/06/07 02:14

http://acm.hdu.edu.cn/showproblem.php?pid=1908

利用二叉树的堆性质

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>using namespace std;struct node{    int l,r,v,pro;    int rnd;}tr[1000005];int size,root,ans;void rturn(int &k){    int t=tr[k].l;    tr[k].l=tr[t].r;    tr[t].r=k;    k=t;}void lturn(int &k){    int t=tr[k].r;    tr[k].r=tr[t].l;    tr[t].l=k;    k=t;}void insert(int &k,int x,int y){    if(k==0)    {        size++;        k=size;        tr[k].v=x;        tr[k].pro=y;        tr[k].rnd=rand();        return;    }    if(x>tr[k].v)    {        insert(tr[k].r,x,y);        if(tr[tr[k].r].rnd<tr[k].rnd)            lturn(k);//把他转到左边    }    else    {        insert(tr[k].l,x,y);        if(tr[tr[k].l].rnd<tr[k].rnd)            rturn(k);    }}void search_min(int &k)//最小值一定在最左的节点上;{    if(tr[k].l==0)    {        ans=tr[k].pro;        k=tr[k].r;        return ;    }     search_min(tr[k].l);}void search_max(int &k)//最大值一定在最右的节点上;{    if(tr[k].r==0)    {        ans=tr[k].pro;        k=tr[k].l;        return ;    }     search_max(tr[k].r);}int main(){    int x,num,y;    while(scanf("%d",&x)!=EOF&&x)    {        ans=0;        if(x==1)        {            scanf("%d%d",&num,&y);            insert(root,y,num);        }        else if(x==2)        {            if(root)            search_max(root);            printf("%d\n",ans);        }        else if(x==3)        {            if(root)            search_min(root);            printf("%d\n",ans);        }    }    return 0;}
0 0