結果

問題 No.2026 Yet Another Knapsack Problem
ユーザー gew1fw
提出日時 2025-06-12 15:56:59
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,821 bytes
コンパイル時間 174 ms
コンパイル使用メモリ 82,688 KB
実行使用メモリ 78,592 KB
最終ジャッジ日時 2025-06-12 15:58:27
合計ジャッジ時間 48,564 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 17 WA * 17 TLE * 2 -- * 6
権限があれば一括ダウンロードができます

ソースコード

diff #

def main():
    import sys
    input = sys.stdin.read().split()
    idx = 0
    N = int(input[idx])
    idx += 1
    items = []
    for _ in range(N):
        c = int(input[idx])
        v = int(input[idx+1])
        items.append((c, v))
        idx += 2

    INF = -10**18
    dp = [ [INF] * (N + 1) for _ in range(N + 1) ]
    dp[0][0] = 0

    for i in range(N):
        c_i, v_i = items[i]
        weight = i + 1  # since type is 1-based
        # Iterate in reverse to avoid overwriting the current state
        # We need to process all possible m, which can be up to c_i
        # But for each m, we can process it as a separate step
        for m in range(0, c_i + 1):
            # For each possible m, process the DP
            # We can optimize by limiting m such that m * weight <= N
            if m * weight > N:
                continue
            # Process in reverse order to prevent using the same m multiple times
            for k_prev in range(N, -1, -1):
                for w_prev in range(N, -1, -1):
                    if dp[k_prev][w_prev] == INF:
                        continue
                    new_k = k_prev + m
                    new_w = w_prev + m * weight
                    if new_k > N or new_w > N:
                        continue
                    new_val = dp[k_prev][w_prev] + m * v_i
                    if new_val > dp[new_k][new_w]:
                        dp[new_k][new_w] = new_val

    # For each k, find the maximum value over all w <= N
    result = [0] * (N + 1)  # result[0] unused
    for k in range(1, N + 1):
        max_val = INF
        for w in range(0, N + 1):
            if dp[k][w] > max_val:
                max_val = dp[k][w]
        result[k] = max_val

    for k in range(1, N + 1):
        print(result[k])

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