結果

問題 No.198 キャンディー・ボックス2
ユーザー lam6er
提出日時 2025-03-20 20:30:48
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 38 ms / 1,000 ms
コード長 833 bytes
コンパイル時間 166 ms
コンパイル使用メモリ 82,840 KB
実行使用メモリ 54,016 KB
最終ジャッジ日時 2025-03-20 20:31:59
合計ジャッジ時間 2,194 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

B = int(input())
N = int(input())
Ci = [int(input()) for _ in range(N)]

sum_total = sum(Ci) + B
max_X = sum_total // N if N != 0 else 0  # Handle N=0, though constraints say N≥1

candidates = set()
for c in Ci:
    candidates.add(c)
    candidates.add(c + 1)
    candidates.add(c - 1)

candidates.add(max_X)
candidates.add(max_X - 1)
candidates.add(max_X + 1)

valid_candidates = [x for x in candidates if 0 <= x <= max_X]

min_ops = float('inf')

for x in valid_candidates:
    sum_op = 0
    take = 0
    put = 0
    for c in Ci:
        if c > x:
            delta = c - x
            take += delta
        elif c < x:
            delta = x - c
            put += delta
        sum_op += abs(c - x)
    
    B_prime = B + take - put
    if B_prime >= 0:
        if sum_op < min_ops:
            min_ops = sum_op

print(min_ops)
0