poj 1990 MooFest // 树状数组
Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 10281 Accepted: 4702 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 3Sample Output
57
题意:给n头牛,每头牛有一个坐标xi,和耳力vi,两各牛需要建立通讯的代价是abs(xi-xj)*max(vi,vj),求所有牛都建立通讯(n*(n-1)/2对)的代价和。
因为涉及max,所以先以vi排序就可以消除max这个限制因素。然后之后就是求i之前的abs和,那么分>a[i],<a[i]的情况,所以需要树状数组维护前缀和,以及比某个数小的个数,动态更新查询。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
#define LL long long
const int max_n = 1e6+6;
struct no{int v,p;};
bool operator<(const no &x,const no &y){return x.v<y.v;}
no a[max_n];
int cnt[max_n],sum[max_n];
void Add(int x,int i,int nn){
while(i<=nn){
sum[i]=sum[i]+x;
cnt[i]++;
i=i+(i&-i);
}
}
void query(int i,int &c,int &s){//小于a[i]的个数和前缀和
while(i>0){
c=c+cnt[i],s=s+sum[i];
i=i-(i&-i);
}
}
int main(){
int n;scanf("%d",&n);for(int i=1;i<=n;i++){
scanf("%d%d",&a[i].v,&a[i].p);
}
sort(a+1,a+1+n);
Add(a[1].p,a[1].p,2e4);
LL ans=0;
for(int i=2;i<=n;i++){
int add=0,sub=0,all=0,addcc=0,subcc=0,allcc=0;
query(a[i].p-1,addcc,sub);
query(2e4,allcc,all);
add=all-sub;subcc=allcc-addcc;
ans=ans+1LL*a[i].v*(add-sub+addcc*a[i].p-subcc*a[i].p);
Add(a[i].p,a[i].p,2e4);
}
printf("%lld",ans);
return 0;
}