1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include <bits/stdc++.h> #define MAX_N 200000 #define MAX_L 1000000 using namespace std; int n, k, tot, rt, ans; vector <int> G[MAX_N+5], E[MAX_N+5]; int s[MAX_N+5], h[MAX_N+5], dis[MAX_N+5], dep[MAX_N+5], mi[MAX_L+5]; bool mrk[MAX_N+5]; void addedge(int u, int v, int c) {G[u].push_back(v), E[u].push_back(c);} void getrt(int u, int fa) { s[u] = 1, h[u] = 0; for (int i = 0; i < (int)G[u].size(); i++) { int v = G[u][i]; if (v == fa || mrk[v]) continue; getrt(v, u); s[u] += s[v], h[u] = max(h[u], s[v]); } h[u] = max(h[u], tot-s[u]); if (h[u] < h[rt]) rt = u; } void calc(int u, int fa) { if (dis[u] <= k) ans = min(ans, dep[u]+mi[k-dis[u]]); for (int i = 0; i < (int)G[u].size(); i++) { int v = G[u][i], c = E[u][i]; if (v == fa || mrk[v]) continue; dep[v] = dep[u]+1, dis[v] = dis[u]+c, calc(v, u); } } void upd(int u, int fa) { if (dis[u] <= k) mi[dis[u]] = min(mi[dis[u]], dep[u]); for (int i = 0; i < (int)G[u].size(); i++) if (G[u][i] != fa && !mrk[G[u][i]]) upd(G[u][i], u); } void clr(int u, int fa) { if (dis[u] <= k) mi[dis[u]] = n; for (int i = 0; i < (int)G[u].size(); i++) if (G[u][i] != fa && !mrk[G[u][i]]) clr(G[u][i], u); } void DFS(int u) { mi[0] = 0, mrk[u] = true; for (int i = 0; i < (int)G[u].size(); i++) { int v = G[u][i], c = E[u][i]; if (mrk[v]) continue; dep[v] = 1, dis[v] = c, calc(v, 0), upd(v, 0); } for (int i = 0; i < (int)G[u].size(); i++) if (!mrk[G[u][i]]) clr(G[u][i], 0); for (int i = 0; i < (int)G[u].size(); i++) { int v = G[u][i]; if (mrk[v]) continue; rt = 0, tot = s[v], getrt(v, 0), DFS(rt); } } int main() { scanf("%d%d", &n, &k); for (int i = 1, u, v, c; i < n; i++) scanf("%d%d%d", &u, &v, &c), u++, v++, addedge(u, v, c), addedge(v, u, c); for (int i = 1; i <= k; i++) mi[i] = n; ans = tot = h[0] = n, getrt(1, 0), DFS(rt); printf("%d", ans == n ? -1 : ans); return 0; }
|