結果

問題 No.1391 ±1 Abs Sum
ユーザー sten_san
提出日時 2021-02-13 11:20:44
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 107 ms / 2,000 ms
コード長 1,660 bytes
コンパイル時間 1,921 ms
コンパイル使用メモリ 195,056 KB
最終ジャッジ日時 2025-01-18 20:05:34
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 34
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

struct uns_t {} uns;
template <typename Element, typename Head, typename ...Args>
auto vec(Element init, Head arg, Args ...args) {
    if constexpr (sizeof...(Args) == 0) return std::vector(arg, init);
    else return std::vector(arg, vec(init, args...));
}
template <typename Element, typename Head, typename ...Args>
auto vec(uns_t, Head arg, Args ...args) {
    return vec(Element(), arg, args...);
}

int main() {
    int64_t n, k; cin >> n >> k;
    auto a = vec<int64_t>(uns, n);
    for (auto &e : a) cin >> e;

    if (k == 0) {
        int64_t now = 0;
        for (int i = 0; i < n; ++i) {
            now -= abs(a[0] - a[i]);
        }

        int64_t ans = now;
        for (int i = 1; i < n; ++i) {
            auto d = a[i] - a[i - 1];
            now -= d * i;
            now += d * (n - i);
            ans = min(ans, now);
        }

        cout << ans << endl;
        return 0;
    }

    int64_t now = 0;
    for (int i = 0; i < n; ++i) {
        if (i < k) {
            now += abs(a[0] - a[i]);
        }
        else {
            now -= abs(a[0] - a[i]);
        }
    }

    int64_t ans = now;

    int l = 0, r = k;
    for (int i = 1; i < n; ++i) {
        auto d = a[i] - a[i - 1];
        auto pl = l, pr = r;
        while (r <= i || (r < n && (abs(a[i] - a[r]) < abs(a[i] - a[l])))) {
            now -= abs(a[i - 1] - a[l]) * 2;
            now += abs(a[i - 1] - a[r]) * 2;
            ++l; ++r;
        }

        now -= d * l;
        now += d * (i - l);
        now -= d * (r - i);
        now += d * (n - r);

        ans = min(ans, now);
    }

    cout << ans << endl;
}

0