Description
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
* 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
Sample Input
4
3 1
2 5
2 6
4 3
Sample Output
57
【题意】有n头牛,排列成一条直线,给出每头牛在直线上的坐标d。每头牛有一个v,如果牛i和牛j想要沟通的话,它们必须用max(v[i],v[j]),消耗的能量为:max(v[i],v[j]) * 它们之间的距离.
问要使所有的牛之间都能沟通(两两之间),总共需要消耗多少能量。
【思路】现将v从小到大排列,使得每次取到的是当前最大的v。
c[1]记录当前牛的数量c[2]记录当前所有牛的d之和。(二维树状数组)
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int N=;
struct node
{
int d,v;
bool operator <(const node &a)const
//从小到大排序,使得当前获得的v一定是出现过最大的。
{
return v<a.v;
}
}moo[N+];
int c[][N+];
int lowbit(int x)
{
return x&(-x);
}
void update(int i,int d,int v)
{
while(d<=N)
{
c[i][d]+=v;
d+=lowbit(d);
}
}
int get_sum(int i,int d)
{
int res=;
while(d)
{
res+=c[i][d];
d-=lowbit(d);
}
return res;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
memset(c,,sizeof(c));
for(int i=;i<=n;i++)
scanf("%d%d",&moo[i].v,&moo[i].d);
sort(moo+,moo++n);
int sum=;//记录所有坐标之和
long long int ans=;
for(int i=;i<=n;i++)
{
int d=moo[i].d;
sum+=d;
update(,d,);//c[1]记录牛数量
update(,d,d);//c[2]记录牛坐标之和
int n1=get_sum(,d);//在i牛及他前面有多少头
int n2=get_sum(,d);//在i牛及他前面的牛坐标和为多少
int tmp1=n1*d-n2;//i左边的坐标差
int tmp2=sum-n2-d*(i-n1);//i右边的坐标差
ans+=(long long int)(tmp1+tmp2)*moo[i].v;
//不用longlong会溢出
}
printf("%lld\n",ans);
}
return ;
}