您的位置:首页 > Web前端

poj1990 moofest 树状数组

2016-03-17 20:09 295 查看
Description

Every year, Farmer John's N (1 <= N <= 20,000) cows attend "MooFest",a social gathering of cows from around the world. MooFest involves a variety of events including haybale stacking, fence jumping, pin the tail on the farmer, and of course, mooing. When the
cows all stand in line for a particular event, they moo so loudly that the roar is practically deafening. After participating in this event year after year, some of the cows have in fact lost a bit of their hearing.

Each cow i has an associated "hearing" threshold v(i) (in the range 1..20,000). If a cow moos to cow i, she must use a volume of at least v(i) times the distance between the two cows in order to be heard by cow i. If two cows i and j wish to converse, they
must speak at a volume level equal to the distance between them times max(v(i),v(j)).

Suppose each of the N cows is standing in a straight line (each cow at some unique x coordinate in the range 1..20,000), and every pair of cows is carrying on a conversation using the smallest possible volume.

Compute the sum of all the volumes produced by all N(N-1)/2 pairs of mooing cows.

Input

* Line 1: A single integer, N

* Lines 2..N+1: Two integers: the volume threshold and x coordinate for a cow. Line 2 represents the first cow; line 3 represents the second cow; and so on. No two cows will stand at the same location.

Output

* Line 1: A single line with a single integer that is the sum of all the volumes of the conversing cows.

Sample Input
4
3 1
2 5
2 6
4 3

Sample Output
57

哈哈哈哈我做出来了.....80%....然后看了题解,不过解法几乎为正解了....

#include<cstring>
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
#define lowbit(i) (-i)&i
#define LL long long
struct node{
LL v,x;
}a[20005];
LL c[2][20050]={0};
bool cmp(node a,node b)
{
return a.v<b.v;
}
LL sum(int i,int d)
{
LL ans=0;
while(i)
{
ans+=c[d][i];
i-=lowbit(i);
}
return ans;
}
void add(int i,LL v,int d)
{
while(i<=20000)
{
c[d][i]+=v;
i+=lowbit(i);
}
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=1;i<=n;i++)scanf("%lld%lld",&a[i].v,&a[i].x);
sort(a+1,a+1+n,cmp);
LL ans=0;
for(i=1;i<=n;i++)
{
LL x=sum(a[i].x,0),y=sum(a[i].x,1);
ans+=(a[i].x*x-y+sum(20000,1)-y-(i-1-x)*a[i].x)*a[i].v;
add(a[i].x,1,0);
add(a[i].x,a[i].x,1);
}
printf("%lld",ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: