Python 代码
N = 210
n, k = map(int, input().split())
h, e, ne, w = [-1] * N, [0] * N, [0] * N, [0] * N
idx = 0
def add(a, b, c):
global idx
e[idx], w[idx] = b, c
h[a], ne[idx] = idx, h[a]
idx += 1
def dfs(cur, pre, dep, num):
global k
dp = [0] * (k + 1)
if dep > k: return dp
for i in range(1, k+1): dp[i] = num
nn = h[cur]
while nn != -1:
son, wei = e[nn], w[nn]
if son != pre:
dp_son = dfs(son, cur, dep + 1, wei)
for i in range(k, -1, -1):
for j in range(k+1):
if (cur == 1 and i - j >= 0) or (cur != 1 and i - j >= 1):
dp[i] = max(dp[i], dp[i-j] + dp_son[j])
nn = ne[nn]
return dp
for _ in range(n - 1):
a, b, c = map(int, input().split())
add(a, b, c)
add(b, a, c)
dp = dfs(1, -1, 0, 0)
print(dp[k])