use proconio::{input, marker::Usize1}; fn main() { input! { n:usize, k:usize, uvw:[(Usize1,Usize1,usize);n-1], } let mut g = vec![vec![]; n]; for &(u, v, _) in uvw.iter() { g[u].push(v); g[v].push(u); } let mut deps = vec![0; n]; let mut leefs = vec![0; n]; f(0, n, 0, &g, &mut deps, &mut leefs); let mut dp = vec![vec![0; k + 1]; n]; for (i, &(u, v, w)) in uvw.iter().enumerate() { for j in 0..=k { let r = if deps[u] < deps[v] { v } else { u }; dp[i + 1][j] = dp[i + 1][j].max(dp[i][j] + w * leefs[r]); if j + w <= k { dp[i + 1][j + w] = dp[i + 1][j + w].max(dp[i][j] + 2 * w * leefs[r]); } } } let ans = *dp[n - 1].iter().max().unwrap(); println!("{}", ans); } fn f( crr: usize, prv: usize, dep: usize, g: &Vec>, deps: &mut Vec, leefs: &mut Vec, ) { deps[crr] = dep; for &nxt in g[crr].iter() { if nxt == prv { continue; } f(nxt, crr, dep + 1, g, deps, leefs); leefs[crr] += leefs[nxt]; } if crr != 0 && g[crr].len() == 1 { leefs[crr] = 1; } }