您的位置:首页 > Web前端

POJ1990 MooFest——树状数组

2011-08-30 15:41 387 查看
维护两个树状数组,一个记录这个坐标所控制的范围内的奶牛个数,另外一个记录这个坐标所控制范围内的奶牛坐标之和。

CODE

Program POJ1990;//By_Poetshy
Const
maxn=20000;
Var
i,n							:Longint;
p,m,ans						:Int64;
v,x,a,h						:Array[1..maxn]of Int64;

Procedure Qsort(l,r:Longint);
var i,j,k,temp:Longint;
begin
i:=l;j:=r;k:=v[(i+j)>>1];
repeat
while v[i]<k do inc(i);
while v[j]>k do dec(j);
if i<=j then
begin
temp:=x[i];x[i]:=x[j];x[j]:=temp;
temp:=v[i];v[i]:=v[j];v[j]:=temp;
inc(i);dec(j);
end;
until i>j;
if i<r then Qsort(i,r);
if l<j then Qsort(l,j);
end;

Function Count(i:Longint):Int64;
begin
Count:=0;
while i>0 do
begin
inc(Count,a[i]);
dec(i,(i)and(-i));
end;
end;

Function Counth(i:Longint):Int64;
begin
Counth:=0;
while i>0 do
begin
inc(Counth,h[i]);
dec(i,(i)and(-i));
end;
end;

Procedure Deal(i:Longint);
var j:Longint;
begin
j:=x[i];
while j<=maxn do
begin
inc(a[j]);
inc(h[j],x[i]);
inc(j,j and(-j));
end;
end;

BEGIN
readln(n);
for i:=1 to n do readln(v[i],x[i]);
Qsort(1,n);
for i:=1 to n do
begin
p:=Count(x[i]);
m:=Counth(x[i]);
inc(ans,v[i]*(p*x[i]-m));
p:=Count(maxn)-p;
m:=counth(maxn)-m;
inc(ans,v[i]*(m-p*x[i]));
Deal(i);
end;
writeln(ans);
END.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: