Let's denote a function
You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of the array.
Print one integer — the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
5 1 2 3 1 3
4
4 6 6 5 5
0
4 6 6 4 4
-8
In the first example:
- d(a1, a2) = 0;
- d(a1, a3) = 2;
- d(a1, a4) = 0;
- d(a1, a5) = 2;
- d(a2, a3) = 0;
- d(a2, a4) = 0;
- d(a2, a5) = 0;
- d(a3, a4) = - 2;
- d(a3, a5) = 0;
- d(a4, a5) = 2.
此题爆了long long(9*1e18),可以考虑用long double存储,输出用%Lf,但需要在C++14下才可以
考虑每个数对答案的贡献,即被当做x和y的次数,然后再处理一下特殊的情况即可
蠢哭了
看了一天
#include<bits/stdc++.h>
using namespace std;
#define maxn 200000+1000
#define LL long long
long long a[maxn];
map<long long,int>q;
int main(){
int n;
cin>>n;
long double sum=0;
for(int j=1;j<=n;j++){
cin>>a[j];
sum+=(j-1)*a[j];
sum-=(n-j)*a[j];
}
for(int j=1;j<=n;j++){
q[a[j]]++;
sum-=q[a[j]-1];
sum+=q[a[j]+1];
}
printf("%.0Lf\n",sum);
}
//-9999999990000000000 longlong 爆这组