結果

問題 No.1782 ManyCoins
ユーザー lam6er
提出日時 2025-03-20 20:40:39
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 998 ms / 2,000 ms
コード長 1,778 bytes
コンパイル時間 165 ms
コンパイル使用メモリ 82,664 KB
実行使用メモリ 108,976 KB
最終ジャッジ日時 2025-03-20 20:40:51
合計ジャッジ時間 9,912 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 48
権限があれば一括ダウンロードができます

ソースコード

diff #

import math
from functools import reduce
import heapq

def main():
    import sys
    input = sys.stdin.read().split()
    N = int(input[0])
    L = int(input[1])
    W = list(map(int, input[2:2+N]))
    
    # Compute gcd of all coins
    def gcd(a, b):
        while b:
            a, b = b, a % b
        return a
    d = reduce(gcd, W)
    
    if L < d:
        print(0)
        return
    
    L_prime = L // d
    W_prime = [w // d for w in W]
    
    if 1 in W_prime:
        print(L_prime)
        return
    
    m = min(W_prime)
    INF = float('inf')
    dp = [INF] * m
    
    for w in W_prime:
        rem = w % m
        if dp[rem] > w:
            dp[rem] = w
    
    heap = []
    for r in range(m):
        if dp[r] != INF:
            heapq.heappush(heap, (dp[r], r))
    
    while heap:
        current_sum, rem = heapq.heappop(heap)
        if current_sum > dp[rem]:
            continue
        for w in W_prime:
            new_sum = current_sum + w
            new_rem = new_sum % m
            if new_sum < dp[new_rem]:
                dp[new_rem] = new_sum
                heapq.heappush(heap, (new_sum, new_rem))
    
    # Find maximum X
    max_x = -1
    valid = True
    for x in dp:
        if x == INF:
            valid = False
            break
        if x > max_x:
            max_x = x
    if not valid:
        print(0)
        return
    X = max_x
    
    count = 0
    L_limit = L_prime
    for r in range(m):
        a_r = dp[r]
        if a_r > L_limit:
            continue
        max_k = min(X, L_limit)
        if a_r > max_k:
            continue
        terms = (max_k - a_r) // m + 1
        count += terms
    
    if X < L_limit:
        count += (L_limit - X)
    
    print(count)

if __name__ == '__main__':
    main()
0