D. Almost Difference
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a.

The second line contains n integers a1a2, ..., an (1 ≤ ai ≤ 109) — elements of the array.

Output

Print one integer — the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

Examples
input
Copy
5
1 2 3 1 3
output
4
input
Copy
4
6 6 5 5
output
0
input
Copy
4
6 6 4 4
output
-8
Note

In the first example:

  1. d(a1, a2) = 0;
  2. d(a1, a3) = 2;
  3. d(a1, a4) = 0;
  4. d(a1, a5) = 2;
  5. d(a2, a3) = 0;
  6. d(a2, a4) = 0;
  7. d(a2, a5) = 0;
  8. d(a3, a4) =  - 2;
  9. d(a3, a5) = 0;
  10. d(a4, a5) = 2


思路:

每个点对答案的贡献= a[i]*(i-1)-sum[i-1]-cnt[a[i]-1]+cnt[a[i]+1]

注意爆long long 

#include<bits/stdc++.h>
#define PI acos(-1.0)
using namespace std;
typedef long long ll;

const int MAX_N=2e5+5;
const int MOD=1e9+7;
const int INF=0x3f3f3f3f;

int a[MAX_N];
ll sum[MAX_N];
map<int,int> mp;

int main(void){
    int n;
    cin >> n;
    memset(sum,0,sizeof sum);
    for(int i=1;i<=n;i++)   scanf("%d",&a[i]);
    for(int i=1;i<=n;i++)   sum[i]=sum[i-1]+1LL*a[i];
    long double ans=0.0;
    mp[a[1]]++;
    for(int i=2;i<=n;i++){
        long double res=(long double)(i-1)*a[i]-sum[i-1];
        res-=mp[a[i]-1];
        res+=mp[a[i]+1];
        mp[a[i]]++;
        ans+=res;
//        cout << res << endl;
    }
    printf("%.0Lf\n",ans+0.1);
    return 0;
}