結果

問題 No.1488 Max Score of the Tree
ユーザー tktk_snsn
提出日時 2021-04-23 22:14:53
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 115 ms / 2,000 ms
コード長 883 bytes
コンパイル時間 231 ms
コンパイル使用メモリ 82,048 KB
実行使用メモリ 76,288 KB
最終ジャッジ日時 2024-07-04 08:11:52
合計ジャッジ時間 3,457 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 29
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

N, K = map(int, input().split())
G = [[] for _ in range(N)]
for _ in range(N-1):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append((b, c))
    G[b].append((a, c))

q = [0]
par = [-1] * N
topo = []
while q:
    s = q.pop()
    topo.append(s)
    for t, d in G[s]:
        if t == par[s]:
            continue
        par[t] = s
        G[t].remove((s, d))
        q.append(t)

cnt = [0]*N
for s, g in enumerate(G):
    if not g:
        cnt[s] = 1

ans = 0
knapsack = []
for s in topo[::-1]:
    p = par[s]
    if p != -1:
        cnt[p] += cnt[s]
    for t, c in G[s]:
        ans += c * cnt[t]
        knapsack.append((c, c * cnt[t]))

dp = [0] * (K + 1)
for w, c in knapsack:
    for i in reversed(range(w, K+1)):
        dp[i] = max(dp[i], dp[i-w]+c)
ans += dp[K]
print(ans)
0