This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "race.h"
#include <bits/stdc++.h>
using namespace std;
const int Lim = 1e6 + 5;
const int maxn = 2e5 + 5;
const int Inf = 1e9 + 7;
typedef pair<int, int> pii;
template<class T> bool minimize(T &res, const T &x) { if (x < res) { res = x; return true; } return false; }
int n, k;
vector<pii> adj[maxn];
int ans[Lim];
int sz[maxn], f[maxn];
int dfs_sz(int u, int p) {
sz[u] = 1;
for (auto [v, w]: adj[u]) if (v != p && !f[v]) {
sz[u] += dfs_sz(v, u);
}
return sz[u];
}
int find_centroid(int u, int p, int n) {
for (auto [v, w]: adj[u]) if (v != p && !f[v])
if (sz[v] * 2 > n) return find_centroid(v, u, n);
return u;
}
int dp[maxn], dist[maxn], dep[maxn];
void add(int u) {
minimize(dp[dist[u]], dep[u]);
}
void sub(int u) {
dp[dist[u]] = Inf;
}
void push(int u, int p) {
if (dist[u] > k) return;
add(u);
for (auto [v, w]: adj[u]) if (v != p && !f[v])
push(v, u);
}
int get(int u, int p) {
if (dist[u] > k) return Inf;
int ans = dp[k - dist[u]] + dep[u];
for (auto [v, w]: adj[u]) if (v != p && !f[v])
minimize(ans, get(v, u));
return ans;
}
void pop(int u, int p) {
if (dist[u] > k) return;
sub(u);
for (auto [v, w]: adj[u]) if (v != p && !f[v])
pop(v, u);
}
void fill(int u, int p) {
if (p == -1) {
dist[u] = 0; dep[u] = 0;
}
for (auto [v, w]: adj[u]) if (v != p && !f[v]) {
dist[v] = dist[u] + w;
dep[v] = dep[u] + 1;
fill(v, u);
}
}
int calc(int r) {
fill(r, -1);
int ans = Inf;
add(r);
for (auto [u, w]: adj[r]) {
minimize(ans, get(u, r));
push(u, r);
}
pop(r, -1);
return ans;
}
int centroid(int u) {
int n = dfs_sz(u, -1);
u = find_centroid(u, -1, n);
int ans = calc(u);
f[u] = true;
for (auto [v, w]: adj[u]) if (!f[v])
ans = min(ans, centroid(v));
f[u] = false;
return ans;
}
int best_path(int N, int K, int H[][2], int L[]) {
n = N; k = K;
for (int i = 0; i < n - 1; ++i) {
int u = H[i][0];
int v = H[i][1];
int w = L[i];
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
for (int i = 0; i <= k; ++i) dp[i] = Inf;
int ans = centroid(0);
if (ans > n) ans = -1;
return 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... |