#include <bits/stdc++.h>
#include "race.h"
using namespace std;
template <typename T>
using v = vector<T>;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, k, n) for (int i = k; i < n; i++)
v<bool> removed;
v<v<pii>> adj;
v<int> sz;
v<pair<bool, int>> a;
set<pair<int, int>> L;
int ans;
int dfs(int n, int p) {
sz[n] = 1;
for (auto x : adj[n]) {
if (x.first == p || removed[x.first]) continue;
sz[n] += dfs(x.first, n);
}
return sz[n];
}
int centroid(int u, int p, int n) {
for (auto x : adj[u]) {
if (x.first == p || removed[x.first]) continue;
else if (sz[x.first]*2 >n) return centroid(x.first, u, n);
}
return u;
}
void dfs1(int n, int p, int w, int d) {
L.insert({w, d});
for (auto x : adj[n]) {
if (x.first == p || removed[x.first]) continue;
if (w+x.second >= a.size()) continue;
dfs1(x.first, n, w+x.second, d+1);
}
}
void build(int u, int p, int K) {
int n = dfs(u, p);
int c = centroid(u, p, n);
a.assign(K+1, {false, 1e9});
for (auto x : adj[c]) {
if (x.first == p || removed[x.first]) continue;
L.clear();
dfs1(x.first, c, x.second, 1);
for (auto y : L) {
if (a[K-y.first].first == true) {
ans = min(ans, y.second + a[K-y.first].second);
}
}
for (auto y : L) {
a[y.first] = {true, min(a[y.first].second, y.second)};
}
}
removed[c] = true;
for (auto x : adj[c]) {
if (removed[x.first] || x.first == p) continue;
build(x.first, c, K);
}
a.clear();
}
int best_path(int N, int K, int H[][2], int L[]) {
int n = N;
adj.resize(n);
removed.assign(n, false);
sz.resize(n);
rep(i, 0, n-1) {
adj[H[i][0]].push_back({H[i][1], L[i]});
adj[H[i][1]].push_back({H[i][0], L[i]});
}
ans = 1e9;
build(0, -1, K);
return (ans == 1e9 ? -1 : ans);
}
# | 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... |