# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
739614 | Nirjhor | Race (IOI11_race) | C++17 | 0 ms | 0 KiB |
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;
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];
}
}
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;
}
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;
}
void decompose (int u = 0) {
trav(u);
int root = centroid(u, sub[u] / 2);
ptr = 0; go(root);
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]);
}
}
}
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;
}
int main() {
int H[][2] = {{0, 1}, {1, 2}};
int L[] = {1, 1};
cout << best_path(3, 3, H, L) << '\n';
return 0;
}