【BZOJ1208】宠物收养所(平衡树,splay)

时间:2024-01-20 12:38:03

题意:见题面

思路:因为每个时刻要么全是人要么全是宠物,所以可以一棵splay解决

维护单点插入,单点删除,求前驱,求后继即可

 var t:array[..,..]of longint;
num,fa:array[..]of longint;
n,cnt,t1,t2,i,root,p,x,y:longint;
ans:int64; procedure rotate(x:longint;var k:longint);
var y,z,l,r:longint;
begin
y:=fa[x]; z:=fa[y];
if t[y,]=x then l:=
else l:=;
r:=-l;
if y=k then k:=x
else
if t[z,]=y then t[z,]:=x
else t[z,]:=x;
fa[x]:=z; fa[y]:=x; fa[t[x,r]]:=y;
t[y,l]:=t[x,r]; t[x,r]:=y;
end; procedure splay(x:longint;var k:longint);
var y,z:longint;
begin
while x<>k do
begin
y:=fa[x]; z:=fa[y];
if y<>k then
begin
if (t[y,]=x)xor(t[z,]=y) then rotate(x,k)
else rotate(y,k);
end;
rotate(x,k);
end;
end; procedure ins(var k:longint;x,last:longint);
begin
if k= then
begin
inc(cnt);
k:=cnt; num[k]:=x;
fa[k]:=last; splay(k,root);
exit;
end;
if x<num[k] then ins(t[k,],x,k)
else ins(t[k,],x,k);
end; procedure del(x:longint);
var k:longint;
begin
splay(x,root);
if t[x,]*t[x,]= then root:=t[x,]+t[x,]
else
begin
k:=t[x,];
while t[k,]> do k:=t[k,];
t[k,]:=t[x,]; fa[t[x,]]:=k;
root:=t[x,];
end;
fa[root]:=;
end; procedure pred(k,x:longint);
begin
if k= then exit;
if num[k]<=x then
begin
t1:=k; pred(t[k,],x);
end
else pred(t[k,],x);
end; procedure succ(k,x:longint);
begin
if k= then exit;
if num[k]>=x then
begin
t2:=k; succ(t[k,],x);
end
else succ(t[k,],x);
end; begin
assign(input,'bzoj1208.in'); reset(input);
assign(output,'bzoj1208.out'); rewrite(output);
readln(n);
for i:= to n do
begin
readln(x,y);
if root= then begin p:=x; ins(root,y,); end
else if p=x then ins(root,y,)
else
begin
t1:=-; t2:=-;
pred(root,y); succ(root,y);
if t1=- then
begin
ans:=ans+num[t2]-y; ans:=ans mod ; del(t2);
end
else if t2=- then
begin
ans:=ans+y-num[t1]; ans:=ans mod ; del(t1);
end
else
if y-num[t1]>num[t2]-y then
begin
ans:=ans+num[t2]-y; ans:=ans mod ; del(t2);
end
else
begin
ans:=ans+y-num[t1]; ans:=ans mod ; del(t1);
end;
end;
end;
writeln(ans);
close(input);
close(output);
end.