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

poj 3481 Double Queue (SBT)

2014-09-03 17:01 330 查看
题意:给定集合,每次插入和删除元素,求最数和最小数。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;

#define maxn 10000000
#define INF 2000000000
int sz[maxn],ch[maxn][2];
int key[maxn],val[maxn],cnt;

void Rotate(int &x,int f){
int y = ch[x][!f];
ch[x][!f] = ch[y][f];
ch[y][f] = x;
sz[y] = sz[x];
sz[x] = sz[ch[x][0]] + sz[ch[x][1]] + 1;
x = y;
}

void Maintain(int &x,int f){
if(sz[ch[ch[x][f]][f]] > sz[ch[x][!f]]) Rotate(x,!f);
else if(sz[ch[ch[x][f]][!f]] > sz[ch[x][!f]]){
Rotate(ch[x][f],f);Rotate(x,!f);
}
else return;
Maintain(ch[x][0],0);
Maintain(ch[x][1],1);
Maintain(x,1);
Maintain(x,0);
}

void Insert(int &x, int k, int p){
if(x==0){
x = ++cnt;sz[x] = 1;
ch[x][0] = ch[x][1] = 0;
key[x] = k;val[x]=p;
}
else{
sz[x]++;
if(p < val[x]) Insert(ch[x][0],k,p);
else Insert(ch[x][1],k,p);
Maintain(x, p>=val[x]);
}
}

int Remove(int &x,int k){
int d_key;
if(!x) return 0;
sz[x]--;
if(val[x]==k || (!ch[x][0] && k<val[x]) || (!ch[x][1] && k>val[x])){
d_key = x;
if(ch[x][0] && ch[x][1]){
int t=Remove(ch[x][0],k+1);
key[x]=key[t];
val[x]=val[t];
}
else x = ch[x][0] + ch[x][1];
return d_key;
}
else return Remove(k<val[x]?ch[x][0]:ch[x][1],k);
}

int Get_max(int x){
while(ch[x][1]) x=ch[x][1];
return x;
}

int Get_min(int x){
while(ch[x][0]) x=ch[x][0];
return x;
}

int main(){
//freopen("1.txt","r",stdin);
int id,a,b,root=0;cnt=0;
while(scanf("%d",&id)!=EOF){
if(id==0) break;
else if(id==2){
if(root==0) printf("0\n");
else{
int t = Get_max(root);
printf("%d\n",key[t]);
Remove(root,val[t]);
}
}
else if(id==3){
if(root==0) printf("0\n");
else{
int t = Get_min(root);
printf("%d\n",key[t]);
Remove(root,val[t]);
}
}
else{
scanf("%d%d",&a,&b);
Insert(root,a,b);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 SBT