結果

問題 No.3051 Make All Divisible
ユーザー rin204
提出日時 2025-02-03 23:05:14
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,257 ms / 2,000 ms
コード長 1,501 bytes
コンパイル時間 283 ms
コンパイル使用メモリ 82,304 KB
実行使用メモリ 76,988 KB
最終ジャッジ日時 2025-06-20 02:21:20
合計ジャッジ時間 9,592 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 32
権限があれば一括ダウンロードができます

ソースコード

diff #

def solve():
    n, K = map(int, input().split())
    A = list(map(int, input().split()))
    A.sort()
    C = [a % K for a in A]
    if sum(C) % K != 0:
        print(-1)
        return

    def ok(x: int) -> bool:
        tot = 0
        x_k = x % K
        for a, c in zip(A, C):
            if a < x:
                tot += a
            else:
                if x < c:
                    return False

                if c <= x_k:
                    tot += x - x_k + c
                else:
                    tot += x - x_k + c - K
        return x <= tot // K

    rr = A[n - K] - 1 + K
    inf = 1 << 62
    max_c = inf
    for d in range(K):
        ma = (rr - d) // K * K + d
        if not ok(ma):
            continue

        l = -1
        r = ma // K
        while r - l > 1:
            mid = (l + r) >> 1
            if ok(mid * K + d):
                r = mid
            else:
                l = mid

        if r * K + d < max_c:
            max_c = r * K + d

    x = max_c
    tot = 0
    max_cnt = 0
    x_k = x % K
    for a, c in zip(A, C):
        if a < x:
            tot += a
        else:
            if c <= x_k:
                tot += x - x_k + c
                if c == x_k:
                    max_cnt += 1
            else:
                tot += x - x_k + c - K

    tot //= K
    if max_c < K:
        max_cnt = 0
    ans = max(max_c, tot - max_cnt)
    if ans == inf:
        print(-1)
    else:
        print(ans)


for _ in range(int(input())):
    solve()
0