結果

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

ソースコード

diff #

import math
from heapq import heappush, heappop

def solve():
    import sys
    N, L = map(int, sys.stdin.readline().split())
    W = list(map(int, sys.stdin.readline().split()))
    
    # Step 1: Compute the GCD of all coin values
    d_all = W[0]
    for w in W[1:]:
        d_all = math.gcd(d_all, w)
    
    # Function to handle the case when GCD is 1
    def compute_new_case(new_W, new_L):
        a = min(new_W)
        if a == 1:
            return new_L
        # Compute dist array using modified Dijkstra's algorithm
        dist = [float('inf')] * a
        heap = []
        # Initialize with each coin's value
        for w in new_W:
            rem = w % a
            if w < dist[rem]:
                dist[rem] = w
                heappush(heap, (w, rem))
        # Process the heap
        while heap:
            k, r = heappop(heap)
            if k > dist[r]:
                continue  # Skip outdated entries
            for w in new_W:
                new_k = k + w
                new_r = (r + w) % a
                if new_k < dist[new_r]:
                    dist[new_r] = new_k
                    heappush(heap, (new_k, new_r))
        # Calculate the answer
        ans = 0
        for r in range(a):
            dr = dist[r]
            if dr == float('inf') or dr > new_L:
                continue
            max_m = (new_L - dr) // a
            ans += max_m + 1
        return ans
    
    # Check if GCD is greater than 1
    if d_all > 1:
        if L < d_all:
            print(0)
            return
        new_L = L // d_all
        new_W = [w // d_all for w in W]
        print(compute_new_case(new_W, new_L))
    else:
        print(compute_new_case(W, L))

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