题意:
每个顾客有个编号和优先级,银行每次可以添加顾客的要求进队列,且保证队列中当前任意顾客的编号和优先级都不同.银行可以执行先服务最大优先级的顾客或者先服务最小优先级的顾客操作.对于每个服务,输出顾客的编号.
题解:
Treap实现二叉树。
节点节点的v值为客户的服务优先级,节点r值为随机的r。
#include<cstdio> #include<iostream> #include<algorithm> #include<cstdlib> #include<cstring> using namespace std; struct node { node *ch[2]; int r,v,info; node(int v,int info):v(v),info(info) { r = rand(); ch[0] = ch[1] = NULL; } int cmp(int x) { if(x==v)return -1; return x<v? 0:1; } }; void Rotate(node* &o,int d) { node *k = o->ch[d^1]; o->ch[d^1] = k->ch[d]; k->ch[d] = o; o = k; } void Insert(node* &o,int v,int info) { if(o==NULL)o = new node(v,info); else { int d = v < o->v? 0:1; Insert (o->ch[d],v,info); if(o->ch[d]->r > o->r) Rotate(o,d^1); } } void Remove(node* &o,int v) { int d = o->cmp(v); if(d==-1) { if(o->ch[0] && o->ch[1]) { int d2 = o->ch[0]->r < o->ch[1]->r?0:1; Rotate(o,d2); Remove(o->ch[d2],v); } else { node *u = o; if(o->ch[0]==NULL) o = o->ch[1]; else o = o->ch[0]; delete u; } } else Remove(o->ch[d],v); } int findmax(node* o) { if(o->ch[1] == NULL) { printf("%d\n",o->info); return o->v; } return findmax(o->ch[1]); } int findmin(node* o) { if(o->ch[0]==NULL) { printf("%d\n",o->info); return o->v; } return findmin(o->ch[0]); } int main() { int op; node *root=NULL; while(scanf("%d",&op)==1&&op) { if(op==1) { int info,v; scanf("%d%d",&info,&v); Insert(root,v,info); } else if(op==2) { if(root == NULL) { cout<<0<<endl; continue; } int v = findmax(root); Remove(root,v); } else { if(root==NULL) { cout<<0<<endl; continue; } int v = findmin(root); Remove(root,v); } } }