Moo Volume
Description Farmer John had received a noise complaint from he neighbor, Farmer Bob, stating that he cows are making too Much noise.
FJ ' s n cows (1 <= n <=) all graze at various locations on a long one-dimensional pasture. The cows is very chatty animals. Every pair of cows simultaneously carries on a conversation (so every cow are simultaneously mooing at all of the N-1 other Cows). When cow I MOOs at Cow J, the volume of this MOO must is equal to the distance between I and J, in order for J to be able To hear the MOO in all. 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 is five cows at locations 1, 5, 3, 2, and 4.
Sample Input
5
1
5
3)
2
4
Sample Output
40
Hint INPUT DETAILS:
There is 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 +2+3=7, and cow at 4 contributes 3+2+1+1=7. The total volume is (10+10+6+7+7) = 40.
Test instructions: Calculates sum =∑ (A[i]-a[j]);
Problem Solving Ideas:
1. The topic of 10,000 points, O (n^2) Violence method is not advisable.
2. Only need to carefully observe, first sort, each item and its next item's function, (repeated use number of times).
Problem Analysis:
Suppose the array is now sorted after:--...-t---...-
K A n-1-k
The number of times each a[i+1]-a[i] Item will be used is (n-1-k) * (k+1) * (A[i+1]-a[i]);
Code:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace Std;
#define MAX 10005
int n;
Long Long A[max];
a long long sum;
int cmp (const void *a,const void *b)
{
Return (* (int*) a)-(* (int*) b);
}
int main ()
{
Freopen ("Input.txt", "R", stdin);
while (scanf ("%d", &n)! = EOF)
{
for (int i = 0; i < n; ++i)
scanf ("%lld", &a[i]);
Qsort (A,n,sizeof (a[0]), CMP);
sum = 0;
for (int i = 0; i < n-1; ++i)
{
Sum + = (A[i+1]-a[i]) * (n-i-1) * (i+1);
}
printf ("%lld\n", sum*2);
}
return 0;
}