#include<bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define bit(mask, i) ((mask >> i) & 1)
#define pb push_back
using namespace std;
void minn(int &x, int y) {x < y ? x : (x = y);}
const int maxN = 200005;
int n, res; ll k; bool check[maxN]; vector<pair<int, ll>> a[maxN]; int sz[maxN];
map<ll, int> mp;
int get_sz(int u, int p) {
sz[u] = 1;
for(auto it : a[u]) {
if(!check[it.fi] && it.fi != p) {
sz[u] += get_sz(it.fi, u);
}
}
return sz[u];
}
int findCentroid(int u, int p, int sized) {
for(auto it : a[u]) {
if(!check[it.fi] && it.fi != p && sz[it.fi] > sized) return findCentroid(it.fi, u, sized);
}
return u;
}
void update(int u, int par, bool upd, ll dist, int depth = 1) {
if(dist > k) return;
if(upd) {
if(mp.find(dist) != mp.end()) {
minn(mp[dist], depth);
} else {
mp[dist] = depth;
}
} else {
if(mp.find(k - dist) != mp.end()) {
minn(res, depth + mp[k - dist]);
}
}
for(auto it : a[u]) {
if(!check[it.fi] && it.fi != par) {
update(it.fi, u, upd, dist + it.se, depth + 1);
}
}
}
void decomposition(int node) {
int root = findCentroid(node, 0, get_sz(node, 0) >> 1);
check[root] = 1;
for(auto it : a[root]) {
if(!check[it.fi]) {
update(it.fi, root, 0, it.se);
update(it.fi, root, 1, it.se);
}
}
mp.clear();
mp[0] = 0;
for(auto it : a[root]) {
if(!check[it.fi]) {
decomposition(it.fi);
}
}
}
int best_path(int N, int K, int H[][2], int L[]) {
n = N, k = K;
for(int i = 1; i < n; ++i) {
int u = H[i - 1][0], v = H[i - 1][1]; ll w = L[i - 1];
++u, ++v;
a[u].pb({v, w}); a[v].pb({u, w});
}
res = INT_MAX;
mp[0] = 0;
decomposition(1);
return (res == INT_MAX ? -1 : res);
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |