排序+简单公式推导
描述
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.
* Lines 2..N+1: The location of each cow (in the range 0..1,000,000,000).
5 1 5 3 2 4
40
There are five cows at locations 1, 5, 3, 2, and 4.
OUTPUT DETAILS:
Cow at 1 contributes 1+2+3+4=10, cow at 5 contributes 4+3+2+1=10, cow at 3 contributes 2+1+1+2=6, cow at 2 contributes 1+1+2+3=7, and cow at 4 contributes 3+2+1+1=7. The total volume is (10+10+6+7+7) = 40.
题目是比较好理解的,关键是找出规律,并且推导出公式
简单题。
题目大意是说求n个牛相互之间距离和,如hint所描述的一样。
首先将这些牛的位置排序。
然后得出有n头牛时,相邻两头牛间距离相加的次数。(如下)
例如5头牛时:设这5头牛为abcde则:
a b c d e
4 3 2 1 >>a叫的时候 (注意,这里: a->e == a->b + b->c + c->d + d->e )
1 3 2 1 >>b叫的时候
1 2 2 1 >>c叫的时候
1 2 3 1 >>d叫的时候
1 2 3 4 >>e叫的时候
求和得:
8 12 12 8
通过尝试,得到如下规律:
n=2 2
n=3 4 4
n=4 6 8 6
n=5 8 12 12 8
n=6 10 16 18 16 10
。。。。。。。。。。。。。。。。。
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100000000;
long long n,i,j,sum;//注意要用long long ,poj好像不能用__int64,这好像有点坑爹,害我wrong了一遍.....
long long a[maxn];
int main()
{
while(~scanf("%lld",&n))
{
for(i=0;i<n;i++)
scanf("%lld",&a[i]);
sum=0;
sort(a,a+n);
for(j=1;j<n;j++)
{
sum=sum+(a[j]-a[j-1])*j*(n-j)*2;
}
printf("%lld\n",sum);
}
return 0;
}