POJ1990 MooFest——树状数组——Pku1990

维护两个树状数组,一个记录这个坐标所控制的范围内的奶牛个数,另外一个记录这个坐标所控制范围内的奶牛坐标之和。

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.

你可能感兴趣的:(树状数组)