codeforces Educational Round 34 D Almost Difference

題意:給你一個數列,求出


求出所有的d(ai, aj) 的和 i和j 滿足 1 <= i <= j <= n。 d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

也就是說,每個數只能向後匹配,不能像前匹配。

一個數,它前面有m個數,後面有n 個數,它是會用n + m次的。只不過情況有兩種。

我們利用map,可以很快找到有那些對於當前數特殊的數,也就是滿足第二種情況的。兩個數之間差爲一,纔會產生爲零的情況(兩個數相等,第一種也可以的)。

所以如果多加,那麼減個一,少加,加個一。


#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
#include<iomanip>
#include<cstdlib>
using namespace std;
typedef long long LL;
typedef long double db;//long double 精度高於18能滿足本題要求
map<int, int> mp;
int main()
{
    int n;
    while(scanf("%d", &n) == 1)
    {
        mp.clear();
        LL sum = 0, ans = 0;
        for(int i = 0; i < n; i++)
        {
            int t;
            scanf("%d", &t);
            ans += 1LL * t * i;//注意這裏可能會超int
            ans -= sum;
            sum += t;
            if(mp.count(t + 1))
            {
                ans += mp[t + 1];
            }
            if(mp.count(t - 1))
            {
                ans -= mp[t - 1];
            }
            mp[t]++;
        }
        cout << fixed << setprecision(0) << ans << '\n';
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章