可以作为入门平衡树的第一道题。
1 试题大意
维护一个序列,支持以下操作:
- 插入一个新的元素,包括它的Key和Value
- 删除Key最小的元素
- 删除Key最大的元素
并在结束时分别输出序列中元素的Key总和与Value总和。
2 分析
平衡树这里用Splay实现。对于删除操作,由于在两端,实现起来较为简单。
3 参考程序
#include <cstdio>
#define lc(x) ((x)==(ch[fa[(x)]][0]))
#define _rst {fa[0]=0;ch[0][0]=ch[0][1]=0;}
using namespace std;
int fa[100005],ch[100005][2],k[100005],v[100005],root=0,ind=0;
long long travel1(int x){
if(!x)return 0;
return travel1(ch[x][0])+travel1(ch[x][1])+k[x];
}
long long travel2(int x){
if(!x)return 0;
return travel2(ch[x][0])+travel2(ch[x][1])+v[x];
}
inline void rotate(int p){
int q=fa[p],y=fa[q],x=ch[q][1]==p;
ch[q][x]=ch[p][x^1]; _rst;
fa[ch[q][x]]=q; _rst;
ch[p][x^1]=q; _rst;
fa[q]=p; _rst;
fa[p]=y; _rst;
if(y)
if(ch[y][0]==q)ch[y][0]=p;
else if(ch[y][1]==q)ch[y][1]=p;
}
inline void splay(int x){
for(int y;y=fa[x];rotate(x))
if(fa[y])rotate((x==lc(y))==(y==lc(fa[y]))?y:x);
root=x;
}
inline void insert(int x,int key,int value){
int y;
while(1){
y=ch[x][k[x]<key];
if(k[y]==key||k[x]==key)return;
if(y==0){
y=++ind;
k[y]=key;
v[y]=value;
ch[y][0]=ch[y][1]=0;
fa[y]=x;
ch[x][k[x]<key]=y;
break;
}
x=y;
}
splay(y);
}
inline void insert(int key,int value){
if(root)insert(root,key,value);
else{
root=++ind;
k[root]=key;
v[root]=value;
ch[root][0]=ch[root][1]=0;
fa[root]=0;
}
}
inline void delmin(int x){
int t=x,l=0;
if(!t)return;
while(ch[t][0])l=t,t=ch[t][0];
if(fa[t]==0){
root=ch[t][1];
fa[ch[t][1]]=0;
ch[t][0]=ch[t][1]=fa[t]=0;
return;
}
ch[l][0]=ch[t][1];
if(ch[t][1])fa[ch[t][1]]=l;
ch[t][0]=ch[t][1]=fa[t]=0;
}
inline void delmax(int x){
int t=x,l=0;
if(!t)return;
while(ch[t][1])l=t,t=ch[t][1];
if(fa[t]==0){
root=ch[t][0];
fa[ch[t][0]]=0;
ch[t][0]=ch[t][1]=fa[t]=0;
return;
}
ch[l][1]=ch[t][0];
if(ch[t][0])fa[ch[t][0]]=l;
ch[t][0]=ch[t][1]=fa[t]=0;
}
int main(){
int t1,t2,t3;
long long s1,s2;
for(;;){
scanf("%d",&t1);
switch(t1){
case 1:
scanf("%d%d",&t2,&t3);
insert(t3,t2);
break;
case 2:
delmax(root);
break;
case 3:
delmin(root);
break;
case -1:
printf("%lld %lld\n",travel2(root),travel1(root));
return 0;
}
}
}