Sum of distance

Title description

There are N cows in different positions on a number line, and each cow calculates the distance to each other cow. Find the sum of these n * (n-1) distances.

Input

1 <= N <= 10000. The position of each cow is an integer in the range of 0 to 1,000,000,000.

First line: N

    The following N lines, with an integer in each line, indicate the position of a cow.

Output

An integer.

Sample input

5
1
5
3
2
4

Sample output

40

prompt

Description:

(1+2+3+4)+(4+3+2+1)

+(2+1+1+2)+(1+1+2+3)

+(3+2+1+1) = 40

Code


#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
#define rep(i,j,k) for(register int i=(j);i<=(k);++i)
using namespace std;
long long n, a[100001];
long long ans = 0; 
template<class T> inline void read(T &x) {
    x=0;
    register char c=getchar();
    register bool f=0;
    while(!isdigit(c))f^=c=='-',c=getchar();
    while(isdigit(c))x=x*10+c-'0',c=getchar();
    if(f)x=-x;
}
int main() {
    read(n);
    rep(i, 1, n) {
        read(a[i]);
    }
    sort(a + 1, a + 1 + n);
    for (register int i = 1; i < n; i ++) {
        ans += (n - i) * (a[i + 1] - a[i]);
    }
    long long cur = ans;
    for (int i = 2; i <= n; i ++) {
        cur += (a[i] - a[i - 1]) * (i - 1 - (n - i + 1));
        ans = ans + cur;
    }
    cout << ans << endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/LJA001162/p/12678577.html
sum