Here is my pseudo code
Sort the cows by their positions.
For each adjencent cows c(i) and c[i-1] (i is from 2 to n)do
calculate the distance d(i) between them
multiply d(i) with (i-1)*(n-i+1) is the contribution of this distance v(i)
The sum of all v(i) times 2 is the result.
Source code:
cpp POJ 2231 Moo Volume
#include <iostream>
#include <algorithm>
using namespace std;
int a[10010],b[10010],n;
__int64 r;
int main(){
int i;
cin>>n;
for(i=1;i<=n/2;i++){
b[i]=(n-i)*i;
b[n-i]=(n-i)*i;
}
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
sort(a,a+n);
r=0;
for(i=1;i<n;i++){
r+=(__int64)(a[i]-a[i-1])*b[i];
}
printf("%I64d",r*2);
return 0;
}