結果

問題 No.615 集合に分けよう
ユーザー pin
提出日時 2017-12-15 13:21:50
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
WA  
実行時間 -
コード長 1,438 bytes
コンパイル時間 794 ms
コンパイル使用メモリ 91,804 KB
実行使用メモリ 5,248 KB
最終ジャッジ日時 2024-12-14 15:56:19
合計ジャッジ時間 2,169 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3 WA * 2
other AC * 10 WA * 16
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <iomanip>
#include <cstring>
#include <algorithm> 
#include <math.h>
#include <queue>
#include <functional>
#include <map>
#include <vector>
#include <string>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;

int n, k;
ll a[100005];
vector<pair<ll, int> > pairs;
int main(void){
    cin >> n >> k;
    for (int i = 0; i < n; i++) cin >> a[i];
    sort(a, a + n);

    for (int i = 0; i < n; i++) {
        if (i == 0){
            pairs.push_back({ a[i + 1] - a[i], i });
        }
        else if (i == n - 1){
            pairs.push_back({ a[i] - a[i - 1], i });
        }
        else{
            pairs.push_back({ a[i + 1] - a[i - 1], i });
        }
    }

    sort(pairs.begin(), pairs.end());

    int cnt = 1;
    bool one[100005];
    for (int i = 0; i < n; i++) one[i] = false;
    one[-1] = one[n] = true;

    for (int i = n - 1; i >= 0; i--){
        int s = pairs[i].second;
        if (one[s - 1] || one[s + 1]){
            one[s] = true;
            cnt++;
        }
        else if (cnt < k - 1){
            one[s] = true;
            cnt += 2;
        }
        if (cnt == k) break;
    }

    ll ans = 0;

    int pos = 0, st;
    while (pos < n){
        st = pos;
        while (!one[pos]){
            pos++;
        }
        if (pos == st){
            pos++;
            continue;
        }
        ans += a[pos - 1] - a[st];
    }

    cout << ans << endl;

}
0