結果
問題 | No.1488 Max Score of the Tree |
ユーザー |
|
提出日時 | 2021-05-04 21:13:17 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 104 ms / 2,000 ms |
コード長 | 1,876 bytes |
コンパイル時間 | 254 ms |
コンパイル使用メモリ | 82,520 KB |
実行使用メモリ | 62,016 KB |
最終ジャッジ日時 | 2024-07-23 16:31:06 |
合計ジャッジ時間 | 3,647 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
def dfs(start=0,goal=None): parents={} p,t=start,0 parents[p]=-2 next_set=[(~p,t),(p,t)] if p==goal: return t while next_set: p,t=next_set.pop() if p>=0: for q,d in edges[p]: if q in parents: continue if q==goal: return t+1 parents[q]=p next_set.append((~q,t+1)) next_set.append((q,t+1)) else: # 帰りがけ処理 p=~p if len(edges[p])==1 and p!=start: cnt[p]=1 else: for q,d in edges[p]: if q==parents[p]: continue cnt[p]+=cnt[q] dp[q]=cnt[q]*d cost_list.append(dp[q]) weight_list.append(d) return -1 def knapsack_weight(single=True): """ 重さが小さい時のナップサックDP :param single: True = 重複なし """ """ dp[weight <= W] = 重さ上限を固定した時の最大価値 """ N=len(weight_list) dp_min = 0 # 総和価値の最小値 dp = [dp_min] * (W + 1) for item in range(N): if single: S = range(W, weight_list[item] - 1, -1) else: S = range(weight_list[item], W + 1) for weight in S: if dp[weight] < dp[weight - weight_list[item]] + cost_list[item]: dp[weight] = dp[weight - weight_list[item]] + cost_list[item] return dp[W] N,K=map(int, input().split()) edges=[[] for _ in range(N)] dp=[0]*N cnt=[0]*N for _ in range(N-1): a,b,c=map(int, input().split()) a-=1 b-=1 edges[a].append((b,c)) edges[b].append((a,c)) W = K cost_list = [] weight_list = [] dfs(start=0,goal=None) S=sum(dp) print(S+knapsack_weight(single=True))