D. Almost Difference Educational Codeforces Round 34 (Rated for Div. 2)

  • 题目链接:http://codeforces.com/contest/903/problem/D
  • 题意:给一个大小为n的整数数组,数组元素 1 <= ai <=1e9, 求 ∑d(ai, aj), (1<= i < j <=n)
    • 这里写图片描述
  • 算法:数论(前缀和)
  • 思路:sum[i] = i*a[i] + (i=0~x-1)∑a[i] + num[a[i]+1] - num[a[i]-1]
    • 通过map 可以得知 i之前a[i]+1 和a[i]-1 的个数
  • 坑点:要用ans 要用long double,因为答案数值爆了long long
#include <bits/stdc++.h>
#define pi acos(-1)
#define fastcin ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL ll_INF = 0x3f3f3f3f3f3f3f3f;//4e18 ~= 2^62
const int maxn =200000 + 10;
const LL mod = 1e9+7;

LL sum[maxn], a[maxn];
map<LL,LL> mp;

int main()
{
    int n; scanf("%d", &n);
    for(int i=0; i<n; i++){
        scanf("%d", &a[i]);
    }
    sum[0]=a[0];
    for(int i=1; i<n; i++) sum[i]+=a[i]+sum[i-1];
    long double ans=0;
    mp[a[0]]++;
    for(int i=1; i<n; i++){
        ans+= i*a[i] - sum[i-1] + mp[a[i]+1] - mp[a[i]-1];
        mp[a[i]]++;
    }
    cout <<fixed << setprecision(0)<< ans << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_37352710/article/details/79974053