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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| # include<cstdio> # include<cstring> # include<algorithm>
using namespace std;
const int INF = 1e9; const int N = 200005; int n, k, u, v, p;
struct Edge{ int nxt, to, dis; }edge[N<<1]; int head[N], edgeNum; void addEdge(int from, int to, int dis){ edge[++edgeNum].nxt = head[from]; edge[edgeNum].to = to; edge[edgeNum].dis = dis; head[from] = edgeNum; }
int root, mxson[N], size[N], sum; bool vis[N]; void findRoot(int x, int f){ size[x] = 1, mxson[x] = 0; for(int i = head[x]; i; i = edge[i].nxt){ if(vis[edge[i].to] || edge[i].to == f) continue; findRoot(edge[i].to, x); size[x] += size[edge[i].to]; mxson[x] = max(mxson[x], size[edge[i].to]); } mxson[x] = max(mxson[x], sum - size[x]); if(mxson[x] < mxson[root]) root = x; }
int ans = INF, tmp[1000005]; void updTmp(int x, int f, int dis, int d){ if(dis <= k) tmp[dis] = min(tmp[dis], d); for(int i = head[x]; i; i = edge[i].nxt){ if(vis[edge[i].to] || edge[i].to == f) continue; updTmp(edge[i].to, x, dis + edge[i].dis, d + 1); } } void updAns(int x, int f, int dis, int d){ if(dis <= k) ans = min(ans, d + tmp[k-dis]); for(int i = head[x]; i; i = edge[i].nxt){ if(vis[edge[i].to] || edge[i].to == f) continue; updAns(edge[i].to, x, dis + edge[i].dis, d + 1); } } void clearTmp(int x, int f, int dis){ if(dis <= k) tmp[dis] = INF; for(int i = head[x]; i; i = edge[i].nxt){ if(vis[edge[i].to] || edge[i].to == f) continue; clearTmp(edge[i].to, x, dis + edge[i].dis); } }
void solve(int x){ vis[x] = 1, tmp[0] = 0; for(int i = head[x]; i; i = edge[i].nxt){ if(vis[edge[i].to]) continue; updAns(edge[i].to, x, edge[i].dis, 1); updTmp(edge[i].to, x, edge[i].dis, 1); } for(int i = head[x]; i; i = edge[i].nxt){ if(vis[edge[i].to]) continue; clearTmp(edge[i].to, x, edge[i].dis); } for(int i = head[x]; i; i = edge[i].nxt){ if(vis[edge[i].to]) continue; root = 0, sum = size[edge[i].to]; findRoot(edge[i].to, 0); solve(root); } }
int main(){ scanf("%d%d", &n, &k); for(int i = 1; i < n; i++){ scanf("%d%d%d", &u, &v, &p); addEdge(u+1, v+1, p); addEdge(v+1, u+1, p); } for(int i = 0; i <= k; i++) tmp[i] = INF; root = 0, mxson[0] = INF, sum = n; findRoot(1, 0); solve(root); if(ans == INF) puts("-1"); else printf("%d\n", ans); return 0; }
|