#include <bits/stdc++.h>
using namespace std;
#define faster ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define int long long
#define FOR(i,a,b) for(int i = a; i <= b; i++)
#define FOD(i,a,b) for(int i = a; i >= b; i--)
#define fi first
#define se second
#define pb push_back
#define ll long long
#define ull unsigned long long
#define lcm(a,b) (a*b)/__gcd(a,b)
#define ii pair<int,int>
#define iii pair<int,pair<int,int>>
#define iv pair<pair<int,int>,pair<int,int>>
const int inf = 1e9;
const ll INF = 1e18;
const int mod = 1e9 + 7;
const int N = 2e5 + 105;
const int dx[] = {-1,0,1,0};
const int dy[] = {0,1,0,-1};
const int dxx[] = {-1,-1,0,1,1,1,0,-1};
const int dyy[] = {0,1,1,1,0,-1,-1,-1};
int n, k, ans;
vector<ii> g[N];
int sze[N];
map<int,int> best;
bool is_centroid[N];
void dfs(int u, int p)
{
sze[u] = 1;
for(ii H : g[u])
{
if(H.fi != p && !is_centroid[H.fi])
{
dfs(H.fi,u);
sze[u] += sze[H.fi];
}
}
}
int find_centroid(int u, int p, int s)
{
for(ii H : g[u])
if(H.fi != p && !is_centroid[H.fi] && sze[H.fi] > s / 2)
return find_centroid(H.fi,u,s);
return u;
}
void cal_dis(int u, int p, int w, int h, int type)
{
if(w > k)
return;
if(type == 2)
{
if(best.count(k-w))
{
ans = min(ans, best[k-w]+h);
}
}
else
{
if(!best.count(w))
best[w] = h;
else
best[w] = min(best[w], h);
}
for(ii H : g[u])
if(H.fi != p && !is_centroid[H.fi])
cal_dis(H.fi,u,w+H.se,h+1,type);
}
void build_centroid(int u)
{
dfs(u,-1);
int centroid = find_centroid(u,-1,sze[u]);
best[0] = 0;
is_centroid[centroid] = 1;
for(ii H : g[centroid])
{
if(is_centroid[H.fi])
continue;
cal_dis(H.fi,centroid,H.se,1,2);
cal_dis(H.fi,centroid,H.se,1,1);
}
best.clear();
for(ii H : g[centroid])
if(!is_centroid[H.fi])
build_centroid(H.fi);
}
void solve()
{
ans = INF;
build_centroid(1);
cout << (ans == INF ? -1 : ans);
}
//void input()
//{
// //freopen("TEST.INP", "r", stdin);
// //freopen("TEST.OUT", "w", stdout);
// cin >> n >> k;
// FOR(i,1,n-1)
// {
// int u, v, w;
// cin >> u >> v >> w;
//// u++;
//// v++;
// g[u].pb({v,w});
// g[v].pb({u,w});
// }
//}
//signed main()
//{
// faster
// input();
// solve();
//}
int best_path(int N, int K, int H[][2], int L[])
{
n = N;
k = K;
FOR(i,1,n-1)
{
int u = H[i][0];
int v = H[i][1];
int w = L[i];
g[u].pb({v,w});
g[v].pb({u,w});
}
solve();
return (ans == INF ? -1 : ans);
}
Compilation message
/usr/bin/ld: /tmp/ccgnx4uM.o: in function `main':
grader.cpp:(.text.startup+0x28): undefined reference to `best_path(int, int, int (*) [2], int*)'
collect2: error: ld returned 1 exit status