fn dfs(cur: usize, prev: usize, paths: &Vec>, leaves: &mut Vec) -> usize { let mut flg = false; let mut ret = 0usize; for &(v, _) in paths[cur].iter() { if v == prev { continue; } flg = true; ret += dfs(v, cur, paths, leaves); } if !flg { ret += 1; } leaves[cur] = ret; ret } fn main() { let mut nk = String::new(); std::io::stdin().read_line(&mut nk).ok(); let nk: Vec = nk.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let n = nk[0]; let k = nk[1]; let mut lines = Vec::with_capacity(n-1); let mut paths = vec![vec![]; n]; for _ in 0..n-1 { let mut temp = String::new(); std::io::stdin().read_line(&mut temp).ok(); let temp: Vec = temp.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let a = temp[0]-1; let b = temp[1]-1; let c = temp[2]; paths[a].push((b, c)); paths[b].push((a, c)); lines.push((a, b, c)); } let mut leaves = vec![0usize; n]; dfs(0, 0, &paths, &mut leaves); let mut dp = vec![vec![0usize; k+1]; n]; let mut score = 0usize; for i in 0..n-1 { let (a, b, c) = lines[i]; let addval = c * leaves[a].min(leaves[b]); score += addval; for j in 0..=k { dp[i+1][j] = dp[i+1][j].max(dp[i][j]); if j+c <= k { dp[i+1][j+c] = dp[i+1][j+c].max(dp[i][j] + addval); } } } println!("{}", dp[n-1][k] + score); }