#include<iostream>
#include<cstring>
#include<cstdio>
#include<ostream>
#include<istream>
#include<algorithm>
#include<queue>
#include<string>
#include<cmath>
#include<set>
#include<map>
#include<stack>
#include<vector>
#define fi first
#define se second
#define pii pair<int,int>
#define inf (1<<30)
#define eps 1e-8
#define ll long long
using namespace std;
const int maxn=110005;
struct SplayTree
{
int son[maxn][2],pre[maxn];
int key[maxn],id[maxn];
int rt,sz;
void init() {
sz=rt=0;
}
void pushUp(int x) {
}
void pushDown(int x) {
}
void Rotate(int x,int c) {
int y=pre[x];
pushDown(y);
pushDown(x);
son[y][!c]=son[x][c];
pre[son[x][c]]=y;
pre[x]=pre[y];
if(pre[x])
son[pre[y]][son[pre[y]][1]==y]=x;
son[x][c]=y;
pre[y]=x;
pushUp(y);
pushUp(x);
}
void Splay(int x,int goal) {
pushDown(x);
while(pre[x]!=goal) {
if(pre[pre[x]]==goal) {
if(son[pre[x]][0]==x)
Rotate(x,1);
else
Rotate(x,0);
}
else {
int y=pre[x],z=pre[y];
if(son[z][0]==y) {
if(son[y][0]==x) {
Rotate(y,1);
Rotate(x,1);
}
else {
Rotate(x,0);
Rotate(x,1);
}
}
else {
if(son[y][1]==x) {
Rotate(y,0);
Rotate(x,0);
}
else {
Rotate(x,1);
Rotate(x,0);
}
}
}
}
pushUp(x);
if(goal==0)
rt=x;
}
void newNode(int f,int& x,int k,int p) {
x=++sz;
pre[x]=f;
key[x]=p;
id[x]=k;
son[x][0]=son[x][1]=0;
}
void Insert(int k,int p) {
if(rt==0) {
rt=++sz;
key[rt]=p;
id[rt]=k;
son[rt][0]=son[rt][1]=0;
return;
}
int x=rt;
while(son[x][key[x]<p])
x=son[x][key[x]<p];
newNode(x,son[x][key[x]<p],k,p);
Splay(sz,0);
}
int getMin() {
int x=rt;
while(son[x][0]) x=son[x][0];
if(x==rt) rt=son[rt][1];
son[pre[x]][0]=son[x][1];
pre[son[x][1]]=pre[x];
return id[x];
}
int getMax() {
int x=rt;
while(son[x][1]) x=son[x][1];
if(x==rt) rt=son[rt][0];
son[pre[x]][1]=son[x][0];
pre[son[x][0]]=pre[x];
return id[x];
}
}spt;
int main()
{
spt.init();
int t,k,p;
while(~scanf("%d",&t)) {
if(!t) break;
if(t==1) {
scanf("%d%d",&k,&p);
spt.Insert(k,p);
}
else if(t==2) {
printf("%d\n",spt.getMax());
}
else {
printf("%d\n",spt.getMin());
}
}
return 0;
}
poj3481 splayTree模板
最新推荐文章于 2021-11-21 15:37:09 发布