結果

問題 No.3051 Make All Divisible
ユーザー suisen
提出日時 2025-01-18 16:03:54
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 9 ms / 2,000 ms
コード長 1,490 bytes
コンパイル時間 914 ms
コンパイル使用メモリ 86,184 KB
実行使用メモリ 7,844 KB
最終ジャッジ日時 2025-06-20 02:20:19
合計ジャッジ時間 1,819 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 32
権限があれば一括ダウンロードができます

ソースコード

diff #

// correct

#include <algorithm>
#include <deque>
#include <iostream>
#include <limits>
#include <numeric>
#include <vector>


void solve(int n, int k, std::vector<long long> a) {
    if (std::accumulate(a.begin(), a.end(), 0LL) % k != 0) {
        std::cout << -1 << '\n';
        return;
    }

    std::deque<long long> dq;

    const long long threshold = k * (k - 1) / 2;
    for (auto& e : a) {
        const long long q = (std::max(0LL, e - threshold) + k - 1) / k;
        e -= q * k;
    }

    std::sort(a.begin(), a.end(), std::greater<long long>());
    dq.push_back(a[0]);
    int next_push = 1;

    constexpr int inf = std::numeric_limits<int>::max();

    int ans = inf;

    int t = std::accumulate(a.begin(), a.end(), 0LL) / k;
    for (;; --t) {
        long long e = dq.front();
        if (e <= t) ans = t;
        dq.pop_front();
        e -= k;
        if (e < 0) break;
        while (next_push < n and a[next_push] >= e) {
            dq.push_back(a[next_push]);
            ++next_push;
        }
        dq.push_back(e);
    }

    if (ans == inf) {
        std::cout << -1 << '\n';
    } else {
        std::cout << ans << '\n';
    }
}


int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int t;
    std::cin >> t;

    while (t--) {
        int n, k;
        std::cin >> n >> k;

        std::vector<long long> a(n);
        for (int i = 0; i < n; ++i) {
            std::cin >> a[i];
        }

        solve(n, k, a);
    }
}
0