您的位置:首页 > 产品设计 > UI/UE

POJ 3481 Double Queue(treap)

2018-01-25 20:36 260 查看
题意:模型大概就是维护一颗平衡树,每次插入会给客户的标号和优先级,查找输出优先级最大或者优先级最小的客户,并且将其从树中删除。

分析:treap最基础的运用

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1000000+5;
struct node
{
int p,k,ra;
int ch[2];
}q[N*2];
int tot,root;
void rotate(int &x, int n)
{
int fl = q[x].ch[0] == n ? 0 : 1;
q[x].ch[fl] = q
.ch[!fl];
q
.ch[!fl] = x;
x = n;
}
void insert(int &x,int n)
{
if(x == 0)
{
x = n; return;
}
if(q
.p < q[x].p)
{
insert(q[x].ch[0],n);
}
else
{
insert(q[x].ch[1],n);
}
if(q[x].ra > q
.ra) rotate(x,n);
}
void add(int k,int p)
{
q[tot].p = p; q[tot].k = k;
q[tot].ra = rand();
q[tot].ch[0] = q[tot].ch[1] = 0;
insert(root,tot++);
}
void delet(int &x,int p)
{
if(x == 0) return;
if(p < q[x].p) delet(q[x].ch[0],p);
else if(p > q[x].p) delet(q[x].ch[1],p);
else
{
if(!q[x].ch[0] || !q[x].ch[1]) x = q[x].ch[0] + q[x].ch[1];
else
{
int l = q[x].ch[0], r = q[x].ch[1];
if(q[l].ra < q[r].ra)
{
rotate(x,l);
delet(q[x].ch[1],p);
}
else
{
rotate(x,r);
delet(q[x].ch[0],p);
}
}
}
}
void find(int r, int fl)
{
if(r == 0)
{
printf("0\n"); return;
}
int res = q[r].k;
int tp = q[r].p;
while(q[r].ch[fl] != 0)
{
r = q[r].ch[fl];
res = q[r].k;
tp = q[r].p;
}
printf("%d\n",res);
delet(root,tp);
}
int main()
{
int op;
tot = 1;
root = 0;
while(scanf("%d",&op) && op)
{
if(op == 2) find(root,1);
else if(op == 3) find(root,0);
else if(op == 1)
{
int nk,np; scanf("%d%d",&nk,&np);
add(nk,np);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: