Description
Nitaa is holding a party at his house. But unfortunately Nitaa has received a noise complaint from his neighbor, Arsenal4, stating that his friends in his room are making too much noise.
Nitaa's N friends (1 <= N <= 10,000) all sit at various locations on a long one-dimensional pasture. The friends are very chatty people. Every pair of friends simultaneously carries on a conversation (so every friend is simultaneously talking with all of the N-1 other friends). When friend i talks with friend j, the volume of this talk must be equal to the distance between i and j, in order for j to be able to hear the conversation at all. Please help Nitaa compute the total volume of sound being generated by all N*(N-1) simultaneous conversation. That is the total volume of conversation between all pairs of friends.
Input
* Line 1: N
* Lines 2..N+1: The location of each friend (in the range 0..1,000,000,000).
Output
Only one line that shows the total volume of the noise.
Sample Input
5
1
5
3
2
4
Sample Output
40
题意:
5
1 5 3 2 4
ans=[(5-1)+(5-3)+(5-2)+(5-4)] + [(3-1)+(5-3)+(3-2)+(4-3)] + [(2-1)+(5-2)+(3-2)+(4-2)] + [ (4-1)+(5-1)+(4-3)+(4-2)]=40
1 #include<cstdio>
2 #define Max 10010
3 #include <algorithm>
4 using namespace std;
5 long long c[Max];
6 long long a[Max]={0},f[Max]={0};
7 int main()
8 {
9 int i,n;
10 while(scanf("%d",&n)!=EOF)
11 {
12 for(i=0;i<n;i++)
13 scanf("%lld",&c[i]);
14 sort(c,c+n);
15 for(i=1;i<n;i++)
16 {
17 a[i]=a[i-1]+i*(c[i]-c[i-1]);
18 f[i]=f[i-1]+a[i];
19 }
20 printf("%lld\n",2*f[n-1]);
21 }
22 return 0;
23 }