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.

转载于:https://www.cnblogs.com/Thispoet/archive/2011/08/30/2160154.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值