結果
| 問題 | 
                            No.198 キャンディー・ボックス2
                             | 
                    
| コンテスト | |
| ユーザー | 
                             norioc
                         | 
                    
| 提出日時 | 2025-04-12 06:08:07 | 
| 言語 | PyPy3  (7.3.15)  | 
                    
| 結果 | 
                             
                                AC
                                 
                             
                            
                         | 
                    
| 実行時間 | 38 ms / 1,000 ms | 
| コード長 | 840 bytes | 
| コンパイル時間 | 402 ms | 
| コンパイル使用メモリ | 82,024 KB | 
| 実行使用メモリ | 53,820 KB | 
| 最終ジャッジ日時 | 2025-04-12 06:08:10 | 
| 合計ジャッジ時間 | 2,652 ms | 
| 
                            ジャッジサーバーID (参考情報)  | 
                        judge4 / judge5 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 4 | 
| other | AC * 26 | 
ソースコード
def int_ternary_search(f, lo: int, hi: int) -> int:
    l = lo
    r = hi
    while r - l > 3:
        m1 = l + (r - l) // 3
        m2 = r - (r - l) // 3
        if f(m1) > f(m2):
            l = m1
        else:
            r = m2
    ind = l
    best = f(l)
    for i in range(l, r+1):
        v = f(i)
        if v < best:
            best = v
            ind = i
    return ind
INF = 1 << 60
B = int(input())
N = int(input())
C = [int(input()) for _ in range(N)]
C.sort(reverse=True)
def f(v: int) -> int:
    t = B
    res = 0
    for c in C:
        if c > v:  # 多い
            t += c - v
            res += c - v
        elif c < v: # 少ない
            if v - c > t: return INF
            t -= v - c
            res += v - c
    return res
lo = min(C)
hi = max(C)
res = int_ternary_search(f, lo, hi)
print(f(res))
            
            
            
        
            
norioc