bzoj 1208 HNOI2004宠物收养所 平衡树

裸平衡树,恢复手感用的

//By BLADEVIL
var
n :longint;
i :longint;
x, y :longint;
t, tot :longint;
key, s, left, right :array[..] of longint;
ft :longint;
a, b :longint;
ans :longint; procedure right_rotate(var t:longint);
var
k :longint;
begin
k:=left[t];
left[t]:=right[k];
right[k]:=t;
s[k]:=s[t];
s[t]:=s[left[t]]+s[right[t]]+;
t:=k;
end; procedure left_rotate(var t:longint);
var
k :longint;
begin
k:=right[t];
right[t]:=left[k];
left[k]:=t;
s[k]:=s[t];
s[t]:=s[left[t]]+s[right[t]]+;
t:=k;
end; procedure maintain(var t:longint;flag:boolean);
begin
if not flag then
if s[left[left[t]]]>s[right[t]] then
right_rotate(t) else
if s[right[left[t]]]>s[right[t]] then
begin
left_rotate(left[t]);
right_rotate(t);
end else exit
else
if s[right[right[t]]]>s[left[t]] then
left_rotate(t) else
if s[left[right[t]]]>s[left[t]] then
begin
right_rotate(right[t]);
left_rotate(t);
end else exit;
maintain(left[t],false);
maintain(right[t],true);
maintain(t,true);
maintain(t,false);
end; procedure insert(var t:longint; v:longint);
begin
if t= then
begin
inc(tot);
t:=tot;
key[t]:=v;
s[t]:=;
left[t]:=;
right[t]:=;
end else
begin
inc(s[t]);
if v<key[t] then insert(left[t],v) else insert(right[t],v);
maintain(t,v>=key[t]);
end;
end; function delete(var t:longint; v:longint):longint;
begin
dec(s[t]);
if (v=key[t]) or (v<key[t]) and (left[t]=) or (v>key[t]) and (right[t]=) then
begin
delete:=key[t];
if (left[t]=) or (right[t]=) then
t:=left[t]+right[t] else
key[t]:=delete(left[t],key[t]+);
end else
if v<key[t] then delete:=delete(left[t],v) else delete:=delete(right[t],v);
end; function pre(var t:longint; v:longint):longint;
begin
if t= then exit(-);
if v<key[t] then pre:=pre(left[t],v) else
begin
pre:=pre(right[t],v);
if pre=- then pre:=key[t];
end;
end; function succ(var t:longint; v:longint):longint;
begin
if t= then exit(-);
if key[t]<=v then succ:=succ(right[t],v) else
begin
succ:=succ(left[t],v);
if succ=- then succ:=key[t];
end;
end; begin
read(n);
ans:=;
t:=; tot:=; s[t]:=; for i:= to n do
begin
read(x,y);
if x=ft then insert(t,y) else
if s[t]= then
begin
ft:=x;
insert(t,y);
end else
begin
a:=pre(t,y); b:=succ(t,y);
if a=- then a:=-maxlongint div ;
if b=- then b:=maxlongint div ;
if abs(b-y)<abs(y-a) then
begin
ans:=(ans+abs(b-y)) mod ;
b:=delete(t,b);
end else
begin
ans:=(ans+abs(y-a)) mod ;
a:=delete(t,a);
end;
end;
end;
writeln(ans); end.
上一篇:Sql订阅发布注意事项


下一篇:Eclipse使用Maven创建Web时错误:Could not resolve archetype org.apache.maven.archetypes:maven-archetype-webap