結果

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

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;
 
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n,k; cin >> n >> k;
    vector<ll> a(n);
    vector<ll> s(n+1);
    for(int i=0;i<n;i++){
        cin >> a[i];
        s[i+1]=s[i]+a[i];
    }
    ll res=2e18;
    k=n-k;
    int pre=n-k;
    if(n==k){
        ll sum=0;
        for(int i=0;i<n;i++){
            sum-=abs(a[0]-a[i]);
        }
        res=min(res,sum);
        sum=0;
        for(int i=0;i<n;i++){
            sum-=abs(a[n-1]-a[i]);
        }
        res=min(res,sum);
    }
    else{
        int fr=0;
        ll psum=0,fsum=0;
        int cnt=k;
        for(int i=n-1;i>=n-k;i--){
            psum+=a[i];
        }
        for(int i=0;i<n;i++){
            while(fr<i and pre<n and abs(a[i]-a[fr])>abs(a[i]-a[pre])){
                psum-=a[pre];
                fsum+=a[fr];
                fr++; pre++;
                cnt--;
            }
            ll tmp=(ll)(i+1)*a[i]-s[i+1];
            tmp+=(s[n]-s[i+1])-(ll)(n-i-1)*a[i];
            tmp-=2*abs(fsum-(ll)fr*a[i]);
            tmp-=2*(psum-(ll)cnt*a[i]);
            res=min(res,tmp);
        }
    }
    cout << res << endl;
}
0