N, K = gets.split.map(&:to_i) graph = Array.new(N) { [] } weight = [] (N - 1).times do a, b, c = gets.split.map(&:to_i) e = weight.size graph[a - 1] << [b - 1, e] graph[b - 1] << [a - 1, e] weight << c end value = [0] * (N - 1) path = [] visited = [false] * N dfs = ->(u) { visited[u] = true has_children = false graph[u].each do |(v, e)| next if visited[v] has_children = true path << e dfs[v] path.pop end unless has_children path.each do |e| value[e] += weight[e] end end } dfs[0] dp = Array.new(K + 1, 0) (0 ... N - 1).each do |i| dp2 = Array.new(K + 1, 0) (0 .. K).each do |w| v = dp[w] v = [v, dp[w - weight[i]] + value[i]].max if w >= weight[i] dp2[w] = v end dp = dp2 end puts value.sum + dp[K]