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>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
const int N = 200010;
bool bad[N];
long long weight[N];
vector <pair <int, int>> g[N];
int sub[N], ans, ptr, h[N], in[N], out[N], flat[N], target;
// compute subtree sizes
void trav (int u, int p = -1) {
sub[u] = 1;
for (auto [v, w] : g[u]) if (v != p and !bad[v]) {
trav(v, u);
sub[u] += sub[v];
}
}
// find centroid
int centroid (int u, int bound, int p = -1) {
for (auto [v, w] : g[u]) if (v != p and !bad[v] and sub[v] > bound) {
return centroid(v, bound, u);
}
return u;
}
// flatten the tree, compute information from root (centroid) to other nodes
void go (int u, int p = -1, int depth = 0, long long sum = 0) {
flat[++ptr] = u, in[u] = ptr;
h[u] = depth, weight[u] = sum;
for (auto [v, w] : g[u]) if (v != p and !bad[v]) {
go(v, u, depth + 1, sum + w);
}
out[u] = ptr;
}
// centroid decomposition routine
void decompose (int u = 0) {
trav(u);
int root = centroid(u, sub[u] / 2);
ptr = 0; go(root);
// data structure for merging two pieces
gp_hash_table <long long, int> smallest;
smallest[0] = 0;
for (auto [u, w] : g[root]) if (!bad[u]) {
// query
for (int i = in[u]; i <= out[u]; ++i) {
int v = flat[i];
long long required = target - weight[v];
if (smallest.find(required) != smallest.end()) {
ans = min(ans, h[v] + smallest[required]);
}
}
// update
for (int i = in[u]; i <= out[u]; ++i) {
int v = flat[i];
if (smallest.find(weight[v]) == smallest.end()) {
smallest[weight[v]] = h[v];
} else {
smallest[weight[v]] = min(smallest[weight[v]], h[v]);
}
}
}
// remove centroid and proceed recursively
bad[root] = true;
for (auto [v, w] : g[root]) if (!bad[v]) decompose(v);
}
int best_path (int N, int K, int H[][2], int L[]) {
for (int i = 0; i < N - 1; ++i) {
int u = H[i][0], v = H[i][1], w = L[i];
g[u].emplace_back(v, w), g[v].emplace_back(u, w);
}
ans = INT_MAX, target = K;
decompose();
if (ans == INT_MAX) 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... |