MooFest

来源:互联网 发布:手机如何设置网络共享 编辑:程序博客网 时间:2024/06/05 14:08
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
43 12 52 64 3
Sample Output

57

先将牛按照听力从小到大排序,然后用两个树状数组分别存储  个数(后面计算一个牛前后各有多少牛用) 和 坐标 (计算前后各有多少牛之后,就需要用坐标值计算音量和啦)  最小音量和  =Σ  当前听力值*(大于当前坐标的坐标和—大于当前坐标的个数*当前坐标+小于于当前坐标的个数*当前坐标—小于当前坐标的坐标和)。   


#include <iostream>#include <stdio.h>#include <algorithm>#include <string.h>#define LL long long#define lowbit(x) x&(-x)using namespace std;const int AX = 20000+666;int n;struct Node{int v;int x;}a[AX];LL b[AX];LL c[AX];void updatenum(int i,int val){while(i<AX){b[i] += val;i += lowbit(i);}}LL getsumnum(int i){LL sum = 0;while(i){sum += b[i];i -= lowbit(i);}return sum;}void update(int i,int val){while(i<AX){c[i] += val;i += lowbit(i);}}LL getsum(int i){LL sum = 0;while(i){sum += c[i];i -= lowbit(i);}return sum;}bool cmp(const Node &a,const Node &b){     return a.v < b.v;}int main(){scanf("%d",&n);for(int i=0;i<n;i++){scanf("%d%d",&a[i].v,&a[i].x);}sort(a,a+n,cmp);LL ans = 0;LL temp = 0;for(int i=0;i<n;i++){LL sums = getsum(a[i].x);int nums = getsumnum(a[i].x);LL sumb =  temp - sums;int numb = i - nums;ans += a[i].v*(nums*a[i].x - sums);ans += a[i].v*(sumb - a[i].x*numb);update(a[i].x,a[i].x);updatenum(a[i].x,1);temp += a[i].x;}cout<<ans<<endl;return 0;}

原创粉丝点击