题目
bzoj权限题。。。
Luogu
Sol
点分治辣,边权非负,k>=1,开个 1e6 1 e 6 的桶就好辣
# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(2e5 + 5);
IL int Input(){
RG int x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}
int n, k, first[_], cnt, mx[_], root, size[_], vis[_];
int tot, ans, t[_ * 5], S[_], deep[_], num[_], tmpS[_];
struct Edge{
int to, w, next;
} edge[_ << 1];
IL void Add(RG int u, RG int v, RG int w){
edge[cnt] = (Edge){v, w, first[u]}, first[u] = cnt++;
}
IL void GetRoot(RG int u, RG int ff){
size[u] = 1, mx[u] = 0;
for(RG int e = first[u]; e != -1; e = edge[e].next){
RG int v = edge[e].to;
if(vis[v] || v == ff) continue;
GetRoot(v, u);
size[u] += size[v];
mx[u] = max(mx[u], size[v]);
}
mx[u] = max(mx[u], tot - size[u]);
if(mx[u] < mx[root]) root = u;
}
IL void GetDeep(RG int u, RG int ff, RG int ss, RG int nn){
if(ss > k) return;
tmpS[++tmpS[0]] = u, S[++S[0]] = u, deep[u] = ss, num[u] = nn;
for(RG int e = first[u]; e != -1; e = edge[e].next){
RG int v = edge[e].to, w = edge[e].w;
if(vis[v] || v == ff) continue;
GetDeep(v, u, ss + w, nn + 1);
}
}
IL void Calc(){
for(RG int i = 1; i <= S[0]; ++i){
RG int d = deep[S[i]];
if(d > k) continue;
if(!t[k - d]) continue;
ans = min(ans, num[S[i]] + t[k - d]);
}
for(; S[0]; --S[0]){
RG int d = deep[S[S[0]]];
if(deep[S[S[0]]] <= k){
if(!t[d]) t[d] = num[S[S[0]]];
else t[d] = min(num[S[S[0]]], t[d]);
}
}
}
IL void Solve(RG int u){
vis[u] = 1;
for(RG int e = first[u]; e != -1; e = edge[e].next){
RG int v = edge[e].to, w = edge[e].w;
if(vis[v]) continue;
GetDeep(v, u, w, 1), Calc();
}
if(t[k]) ans = min(ans, t[k]);
for(; tmpS[0]; --tmpS[0]) if(deep[tmpS[tmpS[0]]] <= k) t[deep[tmpS[tmpS[0]]]] = 0;
for(RG int e = first[u]; e != -1; e = edge[e].next){
RG int v = edge[e].to;
if(vis[v]) continue;
root = 0, tot = size[v];
GetRoot(v, u), Solve(root);
}
}
int main(RG int argc, RG char* argv[]){
freopen("ioi2011-race.in", "r", stdin);
freopen("ioi2011-race.out", "w", stdout);
tot = n = Input(), k = Input(), Fill(first, -1);
for(RG int i = 1; i < n; ++i){
RG int u = Input() + 1, v = Input() + 1, w = Input();
Add(u, v, w), Add(v, u, w);
}
ans = mx[0] = n + 1, GetRoot(1, 0), Solve(root);
printf("%d\n", ans == n + 1 ? -1 : ans);
return 0;
}