求距离为k的最少边数 我们可以使用dp的思想
每次如果距离 为 tmp 那么我们就可以 使用 k-tmp的值
然后再更新一遍
注意点分治 里不要使用 memset 否则大概率可能tle
#include <bits/stdc++.h>
using namespace std;
//#define int long long
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<int> vi;
#define fi first
#define se second
#define pb push_back
#define inf 1ll<<62
#define endl "\n"
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define de_bug(x) cerr << #x << "=" << x << endl
#define all(a) a.begin(),a.end()
#define IOS std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define fer(i,a,b) for(int i=a;i<=b;i++)
#define der(i,a,b) for(int i=a;i>=b;i--)
const int mod = 1e9 + 7;
const int N = 1e6 + 10;
const int M = 2e6 + 10;
int n, k;
int ans, cnt, idx2;
int h[N], e[M], ne[M], w[M];
int vis[N];
pii q[N];
pii p[N];
int dp[N];
void add(int a,int b,int c){
e[cnt]=b,w[cnt]=c,ne[cnt]=h[a],h[a]=cnt++;
}
void get_dis(int u, int fa, int dis, int cn, int& idx) {
if(vis[u] || dis > k)return ;
q[idx++] = {dis, cn};
for(int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if(v == fa)continue;
get_dis(v, u, dis + w[i], cn + 1, idx);
}
}
int get_sz(int u, int fa) {
if(vis[u])return 0;
int ans = 1;
for(int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if(v == fa)continue;
ans += get_sz(v, u);
}
return ans;
}
int get_wc(int u, int fa, int tot, int &wc ) {
if(vis[u])return 0;
int sum = 1;
int ma = 0;
for(int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if(v == fa)continue;
int t = get_wc(v, u, tot, wc);
ma = max(ma, t);
sum += t;
}
ma = max(ma, tot - sum);
if(ma <= tot / 2) {
wc = u;
}
return sum;
}
void calc(int u) {
if(vis[u])return ;
get_wc(u, -1, get_sz(u, -1), u);
vis[u] = 1;
//cout<<u<<endl;
int idx1 = 0;
for(int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
idx2 = 0;
get_dis(v, -1, w[i], 1, idx2);
for(int j = 0; j < idx2; j++) {
// cout << q[j].fi << " " << q[j].se << endl;
if(q[j].fi == k)
ans = min(ans, q[j].se);
ans = min(ans, dp[k - q[j].fi] + q[j].se);
p[idx1++] = q[j];
}
for(int j = 0; j < idx2; j++) {
dp[q[j].fi] = min(dp[q[j].fi], q[j].se);
}
}
for(int i = 0; i < idx1; i++) {
dp[p[i].fi] = 1<<30;
}
for(int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
calc(v);
}
}
void solve() {
cin >> n >> k;
ans = 1<<30;
memset(h, -1, sizeof(h));
fer(i, 1, n - 1) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
for(int i = 0; i < N; i++)dp[i] = 1<<30;
calc(0);
if(ans == (1<<30))cout << -1 << endl;
else cout << ans << endl;
}
int main() {
IOS;
int _ = 1;
//cin>>_;
while( _-- )
solve();
}