Problem M:Moo Volume(POJ-2231)

Problem Description

Farmer John has received a noise complaint from his neighbor, Farmer Bob, stating that his cows are making too much noise. 

FJ's N cows (1 <= N <= 10,000) all graze at various locations on a long one-dimensional pasture. The cows are very chatty animals. Every pair of cows simultaneously carries on a conversation (so every cow is simultaneously MOOing at all of the N-1 other cows). When cow i MOOs at cow j, the volume of this MOO must be equal to the distance between i and j, in order for j to be able to hear the MOO at all. Please help FJ compute the total volume of sound being generated by all N*(N-1) simultaneous MOOing sessions.

Input

* Line 1: N 

* Lines 2..N+1: The location of each cow (in the range 0..1,000,000,000).

Output

There are five cows at locations 1, 5, 3, 2, and 4.

Sample Input

5
1
5
3
2
4

Sample Output

40

————————————————————————————————————————————————————

题意:在一条数轴上,给出 n 头奶牛的位置,每头牛对其他 n-1 头牛发出声音,它们发出声音的大小即它们的距离,求所有牛发出的声音和。

思路:实质是要求所有点的距离差的和,先排序,假设第 i 头牛发出的声音是 ans[i] ,第 i 头牛的坐标是 cow[i],则两头牛的距离是 cow[i]-cow[i-1],简单推导可以知道第 i 头牛向其前 i-1 头发出的声音都要比 i-1 少一个单位距离,即:ans[i]=ans[i-1] +(cow[i]-cow[i-1])*(i-1) ,同理,第 i 头牛向其后 i+1 头牛发出的声音都要比 i-1 多一个单位距离,也即:ans[i]=ans[i+1] + i*(cow[i+1]-cow[i)*(n-i)

由于数据范围很大,注意使用 long long

Source Program

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<vector>
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define N 10001
#define MOD 123
#define E 1e-6
using namespace std;
long long ans[N],cow[N];
int main()
{
    int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
        scanf("%d",&cow[i]);

	sort(cow+1,cow+n+1);

	long long sum=0;
    ans[1]=0;
	for(int i=2;i<=n;i++)
    {
        ans[i]=ans[i-1]+(cow[i]-cow[i-1])*(i-1);
        sum+=ans[i];
    }
    ans[n]=0;
    for(int i=n-1;i>=1;i--)
    {
        ans[i]=ans[i+1]+(cow[i+1]-cow[i])*(n-i);
        sum+=ans[i];
    }

	printf("%lld\n",sum);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/u011815404/article/details/81267600