题目链接:http://codeforces.com/problemset/problem/903/D
思路:对于一个给定的a[x]来说,对于 d(a[1],a[x]) + d(a[2],a[x])+.......+d(a[i].a[x])的结果是 i * a[x] - sum(sum为前x-1项元素的和) + (a[i] - a[x] == 1的所有数的个数,即所有等于a[x]+1的数的个数) - (a[x] - a[i] == 1 的所有数的个数,即所有等于a[x] - 1 的数的个数)
setprecision(0) 和 fixed 控制输出的精度
#include <bits/stdc++.h>
#define LL long long
#define ld long double
using namespace std;
int n;
LL a[210000];
int main(){
scanf("%d",&n);
map<LL, LL> mp;
for(int i = 0; i < n; i ++) scanf("%lld",&a[i]);
ld ans = 0, sum = 0;
for(int i = 0; i < n; i ++){
ans += i * a[i] - sum + mp[a[i] + 1] - mp[a[i] - 1];
mp[a[i]] ++;
sum += a[i];
}
cout << fixed << setprecision(0) << ans << endl;
return 0;
}