結果
問題 | No.196 典型DP (1) |
ユーザー |
![]() |
提出日時 | 2025-03-20 20:53:11 |
言語 | PyPy3 (7.3.15) |
結果 |
TLE
|
実行時間 | - |
コード長 | 1,836 bytes |
コンパイル時間 | 206 ms |
コンパイル使用メモリ | 82,728 KB |
実行使用メモリ | 109,548 KB |
最終ジャッジ日時 | 2025-03-20 20:53:38 |
合計ジャッジ時間 | 9,963 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | -- * 3 |
other | AC * 33 TLE * 1 -- * 7 |
ソースコード
MOD = 10**9 + 7 n, K = map(int, input().split()) edges = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) edges[a].append(b) edges[b].append(a) # Build the tree structure with parent-child relationships from collections import deque parent = [-1] * n children = [[] for _ in range(n)] queue = deque([0]) parent[0] = -1 while queue: u = queue.popleft() for v in edges[u]: if parent[v] == -1 and v != 0: parent[v] = u children[u].append(v) queue.append(v) # Compute the size of each subtree using post-order traversal size = [1] * n post_order = [] stack = [(0, False)] while stack: u, visited = stack.pop() if visited: post_order.append(u) for v in children[u]: size[u] += size[v] else: stack.append((u, True)) # Push children in reverse order to process them in correct post-order for v in reversed(children[u]): stack.append((v, False)) # Initialize the DP table dp = [[0] * (K + 1) for _ in range(n)] for u in post_order: # Initialize temp for not selecting u, start with 1 way to select 0 vertices temp = [0] * (K + 1) temp[0] = 1 # Merge all children's DP tables into temp for v in children[u]: new_temp = [0] * (K + 1) for k in range(K + 1): if temp[k] == 0: continue for l in range(K - k + 1): if dp[v][l]: new_temp[k + l] = (new_temp[k + l] + temp[k] * dp[v][l]) % MOD temp = new_temp # Consider selecting u if possible if size[u] <= K: temp[size[u]] = (temp[size[u]] + temp[0]) % MOD # Assign the computed temp to dp[u] for k in range(K + 1): dp[u][k] = temp[k] print(dp[0][K] % MOD)