#include using namespace std; typedef long long ll; typedef long double ld; #define REP(i, n) for (int i = 0; i < (n); ++i) #define REPR(i, n) for (int i = n - 1; i >= 0; --i) #define FOR(i, m, n) for (int i = m; i < n; ++i) #define FORR(i, m, n) for (int i = m; i >= n; --i) #define ALL(v) (v).begin(),(v).end() #define ALLR(v) (v).rbegin(),(v).rend() #define fi first #define se second #define PB push_back #define EB emplace_back using P = pair; template using PQ = priority_queue; template using QP = priority_queue,greater>; templatevoid debug(const T &v,ll h,ll w){for(ll i=0;ivoid debug(const T &v,ll n){for(ll i=0;ivoid debug(const vector&v){debug(v,v.size());} templatevoid debug(const vector>&v){for(auto &vv:v)debug(vv,vv.size());} templatevoid debug(stack st){while(!st.empty()){cout<void debug(queue st){while(!st.empty()){cout<void debug(deque st){while(!st.empty()){cout<void debug(PQ st){while(!st.empty()){cout<void debug(QP st){while(!st.empty()){cout<void debug(const set&v){for(auto z:v)cout<void debug(const multiset&v){for(auto z:v)cout<void debug(const array &a){for(auto z:a)cout<void debug(const map&v){for(auto z:v)cout<<"["<bool chmax(T &a, const T &b) { if (abool chmin(T &a, const T &b) { if (b> n >> k; vector>> e(n); vector h(n); REP(i,n-1){ int a,b,c;cin >> a >> b >> c; a--,b--; e[a].PB({b,c}); e[b].PB({a,c}); h[a]++,h[b]++; } vector d(n),x(n); vector w,v; auto dfs=[&](auto &&dfs,int cur,int pre=-1)->void{ for(auto to:e[cur]){ if(to.fi==pre) continue; d[to.fi]=d[cur]+to.se; dfs(dfs,to.fi,cur); x[cur]+=x[to.fi]; w.PB(to.se); v.PB(to.se*x[to.fi]); } if(h[cur]==1) x[cur]++; }; dfs(dfs,0); vector> dp(n,vector(k+1,-1)); dp[0][0]=0; REP(i,n-1){ REP(j,k+1){ if(dp[i][j]==-1) continue; chmax(dp[i+1][j],dp[i][j]); if(j+w[i]<=k) chmax(dp[i+1][j+w[i]],dp[i][j]+v[i]); } } int ans=0; REP(i,k+1) chmax(ans,dp[n-1][i]); REP(i,n) if(h[i]==1) ans+=d[i]; cout << ans << endl; }