http://poj.org/problem?id=3481
题意很简单,就是给你很多用户的信息,叫你找出某一时刻的最大值,或最小值的id并将他从队列中删除。
这道题做法有很多很多,set都可以过去,我就把这道题当作Treap的练习题;
下面来一个简单的模板。
///#include <bits/stdc++.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<time.h>
#include<iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
/**namespace io {
const int SIZE = 1e7 + 10;
char inbuff[SIZE];
char *l, *r;
inline void init() {
l = inbuff;
r = inbuff + fread(inbuff, 1, SIZE, stdin);
}
inline char gc() {
if (l == r) init();
return (l != r) ? *(l++) : EOF;
}
void read(int &x) {
x = 0; char ch = gc();
while (!isdigit(ch)) ch = gc();
while (isdigit(ch)) x = x * 10 + ch - '0', ch = gc();
}
} using io::read;*/
const int inf=0x3f3f3f3f;
const int N=1e7+10;
const int M=20;
struct Treap
{
int l,r;
int val,dat,id;
int cnt,sz;
}t[N];
int tot,root,n;
void init(){ tot=0;}
int New(int val,int id)
{
t[++tot].val=val;t[tot].dat=rand();
t[tot].l=t[tot].r=0;
t[tot].cnt=t[tot].sz=1;
t[tot].id=id;
return tot;
}
void update(int p){t[p].sz=t[t[p].l].sz+t[t[p].r].sz+t[p].cnt;}
void build(){New(-inf,0);New(inf,inf);root=1;t[1].r=2;update(root);}
void zig(int &p){int q=t[p].l;t[p].l=t[q].r,t[q].r=p,p=q;update(t[p].r),update(p);}
void zag(int &p){int q=t[p].r;t[p].r=t[q].l,t[q].l=p,p=q;update(t[p].l),update(p);}
void Insert(int &p,int val,int id)
{
if(p==0){
p=New(val,id);
return;
}
if(val==t[p].val){
t[p].cnt++,update(p);return;
}
if(val<t[p].val){
Insert(t[p].l,val,id);
if(t[p].dat<t[t[p].l].dat) zig(p);
}
else{
Insert(t[p].r,val,id);
if(t[p].dat<t[t[p].l].dat) zag(p);
}
update(p);
}
void Remove(int &p,int val)
{
if(p==0) return;
if(val==t[p].val){
if(t[p].cnt>1){
t[p].cnt--,update(p);
return;
}
if(t[p].l||t[p].r){
if(t[p].r==0||t[t[p].l].dat>t[t[p].r].dat) zig(p),Remove(t[p].r,val);
else zag(p),Remove(t[p].l,val);
update(p);
}
else p=0;
return;
}
if(val<t[p].val) Remove(t[p].l,val);
else Remove(t[p].r,val);
update(p);
}
int GetVal(int p,int rk)
{
if(p==0) return 0;
if(t[t[p].l].sz>=rk) return GetVal(t[p].l,rk);
if(t[t[p].l].sz+t[p].cnt>=rk) return p;
return GetVal(t[p].r,rk-t[t[p].l].sz-t[p].cnt);
}
int main()
{
int opt,l,p,tt,cnt=0;
build();
while(~scanf("%d",&opt)&&opt){
if(opt==1){
scanf("%d%d",&l,&p);
Insert(root,p,l);
cnt++;
}
else if(opt==2){
tt=GetVal(root,cnt+1);
if(tt!=0&&tt!=1) Remove(root,t[tt].val);
printf("%d\n",t[tt].id);
if(cnt>0)cnt--;
}
else{
tt=GetVal(root,2);
if(tt!=0&&tt!=1) Remove(root,t[tt].val);
printf("%d\n",t[tt].id);
if(cnt>0)cnt--;
}
}
return 0;
}