平衡树模板 bzoj 3224

program t3224;

var
tr:array[-1..1000000,1..2] of int64;
num,fa,size,quan:array[-1..1000000] of int64;
i,n,sz,rt:longint;
x,y:int64;

function judge(a:boolean):longint;
begin
if a then exit(1) else exit(2);
end;

procedure rotate(k:longint);
var
f,ff,lr,szlr,szk,x:longint;
begin
f:=fa[k]; ff:=fa[f];
x:=judge(tr[f,1]=k); lr:=tr[k,3-x];
szlr:=size[lr]; szk:=size[k];
tr[ff,judge(tr[ff,1]=f)]:=k; fa[k]:=ff; size[k]:=size[f];
tr[k,3-x]:=f; fa[f]:=k;
tr[f,x]:=lr; fa[lr]:=f; size[f]:=size[f]-szk+szlr;
end;

procedure splay(k:longint);
var
f,ff,p,g1,g2:longint;
begin
if k=-1 then exit;
p:=k;
while fa[p]<>0 do
begin
f:=fa[p]; ff:=fa[f];
if ff=0 then begin rotate(p); break; end;
g1:=judge(tr[f,1]=p); g2:=judge(tr[ff,1]=f);
if (g1=g2)and(fa[ff]=0) then begin rotate(p); rotate(p); continue; end;
if g1=g2 then begin rotate(f); rotate(p); end;
if g1<>g2 then begin rotate(p); rotate(p); end;
end;
rt:=p;
end;

procedure inse(data:int64);
var
p,f:longint;
begin
p:=rt;
f:=0;
while p<>-1 do
begin
f:=p;
size[f]:=size[f]+1;
if data=num[p] then begin inc(quan[p]); splay(p); exit; end;
if data>num[p]
then begin p:=tr[p,2]; continue; end;
if data<num[p]
then p:=tr[p,1];
end;
inc(sz); num[sz]:=data; quan[sz]:=1; size[sz]:=1;
fa[sz]:=f; tr[sz,1]:=-1; tr[sz,2]:=-1;
if data>num[f] then tr[f,2]:=sz else tr[f,1]:=sz;
splay(sz);
end;

function findrank(data:int64):int64;
var
p:longint;
begin
p:=rt;
while true do
begin
if num[p]>data then p:=tr[p,1];
if num[p]<data then p:=tr[p,2];
if num[p]=data then break;
end;
splay(p);
exit(size[tr[p,1]]+1);
end;

procedure dele(data:int64);
var
p,p1,p2:longint;
begin
p:=rt;
while true do
begin
if num[p]>data then p:=tr[p,1];
if num[p]<data then p:=tr[p,2];
if num[p]=data then break;
end;
splay(p);
if quan[p]>1 then begin dec(quan[p]); dec(size[p]); exit; end;
if quan[p]=1
then begin
p1:=tr[rt,1];
while tr[p1,2]<>-1 do
p1:=tr[p1,2];
p2:=tr[rt,2];
while tr[p2,1]<>-1 do
p2:=tr[p2,1];
splay(p2); splay(p1);
dec(size[rt]);
dec(size[tr[rt,2]]);
tr[tr[rt,2],1]:=-1;
end;
end;

function pre(data:int64):int64;
var
p:longint;
begin
inse(data);
p:=tr[rt,1];
while tr[p,2]<>-1 do
p:=tr[p,2];
dele(data);
exit(num[p]);
end;

function suc(data:int64):int64;
var
p:longint;
begin
inse(data);
p:=tr[rt,2];
while tr[p,1]<>-1 do
p:=tr[p,1];
dele(data);
exit(num[p]);
end;

function finddata(rank:longint):int64;
var
p:longint;
begin
p:=rt;
inc(rank);
while not((size[tr[p,1]]<rank)and(size[tr[p,1]]+quan[p]>=rank)) do
begin
if size[tr[p,1]]>=rank then begin p:=tr[p,1]; continue; end;
if size[tr[p,1]]<rank then begin rank:=rank-size[tr[p,1]]-quan[p]; p:=tr[p,2]; end;
end;
exit(num[p]);
end;

begin
sz:=0;
rt:=-1;
size[0]:=0;
inse(maxlongint*1000);
inse(-maxlongint*1000);
for i:=1 to n do
begin