裸的平衡树,Splay和Treap均可水过,我的splay也是debug了好久….
#include<cstdio>
#define MAXN 300005
struct node {
int v, cnt, sz, ch[2], f;
}t[MAXN];
int rt, sz, n;
#define Upd(r) {t[r].sz = t[t[r].ch[0]].sz + t[t[r].ch[1]].sz + t[r].cnt;}
void rot(int x)
{
int y = t[x].f, z = t[y].f;
bool f = (t[y].ch[1] == x);
t[y].ch[f] = t[x].ch[f^1];
if(t[y].ch[f]) t[t[y].ch[f]].f = y;
t[x].ch[f^1] = y; t[y].f = x;
t[x].f = z;
if(z) t[z].ch[t[z].ch[1]==y] = x;
Upd(y);
}
void Spaly(int r, int tp) {
for(int y, z; (y = t[r].f) != tp; rot(r)) {
z = t[y].f;
if(z == tp) continue;
if( (t[z].ch[0] == y) == (t[y].ch[0] == r) ) rot(y);
else rot(r);
}
if(!tp) rt = r; Upd(r);
}
void Ins(int r, int x) {
int y = 0;
while(r && t[r].v != x) { y = r; r = t[r].ch[x > t[r].v]; }
if(r) ++ t[r].cnt;
else {
r = ++ sz; t[r].sz = t[r].cnt = 1;
t[r].v = x; t[r].f = y; if(y) t[y].ch[x > t[y].v] = r;
}
Spaly(r, 0);
}
void Find(int v) {
int x = rt; if(!x) return;
while(t[x].ch[v > t[x].v] && t[x].v != v) x = t[x].ch[v > t[x].v];
Spaly(x, 0);
}
int Ran(int v) {
Find(v);
return t[t[rt].ch[0]].sz;
}
int Kth(int x)
{
int y=rt,p;
if(x>t[rt].sz)return 0;
while(1)
{
p=t[y].ch[0];
if(t[p].sz+t[y].cnt<x) {
x-=t[p].sz+t[y].cnt;
y=t[y].ch[1];
}
else if(t[p].sz>=x) y=p;
else return t[y].v;
}
}
int Nxt(int x, bool f)
{
Find(x);
if((t[rt].v>x&&f)||(t[rt].v<x&&!f)) return rt;
int p = t[rt].ch[f];
while(t[p].ch[f^1]) p = t[p].ch[!f];
return p;
}
void Del(int v) {
int p = Nxt(v, 0), s = Nxt(v, 1);
Spaly(p, 0); Spaly(s, p);
p = t[s].ch[0];
if(t[p].cnt > 1) -- t[p].cnt, Spaly(p, 0);
else t[s].ch[0] = 0;
}
char c, f;
inline void GET(int &n) {
n = 0; f = 1;
do {c = getchar(); if(c == '-') f = -1;} while(c > '9' || c < '0');
while(c >= '0' && c <= '9') {n=n*10+c-'0';c=getchar();}
n *= f;
}
int main() {
freopen("phs.in","r",stdin);
freopen("phs.out","w",stdout);
GET(n);
int opt,x;
Ins(rt, -0x7fffffff); Ins(rt, +0x7fffffff);
for(int i=1; i<=n; i++) {
GET(opt); GET(x);
switch(opt) {
case 1: Ins(rt,x); break;
case 2: Del(x); break;
case 3: printf("%d\n",Ran(x)); break;
case 4: printf("%d\n",Kth(x+1)); break;
case 5: printf("%d\n",t[Nxt(x, 0)].v); break;
case 6: printf("%d\n",t[Nxt(x, 1)].v); break;
}
}
return 0;
}
HelenKeller
2016.7.4