# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
889643 | asdfgrace | 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 <bits/stdc++.h>
#include "race.h"
using namespace std;
/*
start at the centroid
consider all paths whose lca is the centroid of the tree
try solving each of these in o(n)?
can we knapsack?
consider root & sum of weights on paths to each node
do a dfs
then for each node
search for a matching path
*/
int best_path(int N, int K, int H[][2], int L[]) {
int ans = 1e9;
vector<vector<pair<int, int>>> edges(N);
for (int i = 0; i < N - 1; i++) {
edges[H[i][0]].push_back({H[i][1], L[i]});
edges[H[i][1]].push_back({H[i][0], L[i]});
}
vector<multiset<int>> at(k + 10);
at[0].insert(0);
vector<int> sz(N, 1), val(N, 0), dep(N, 0);
vector<bool> visited(N, false);
function<void(int, int)> dfs_sz = [&] (int node, int par) {
sz[node] = 1;
for (auto [next, wt] : edges[node]) {
if (next == par || visited[next]) continue;
dfs_sz(next, node);
sz[node] += sz[next];
}
};
function<int(int, int, int)> centroid = [&] (int node, int par, int s) {
for (auto [next, wt] : edges[node]) {
if (next != par && !visited[next] && sz[next] > s / 2) {
return centroid(next, node, s);
}
}
return node;
};
function<void(int, int)> dfs_val = [&] (int node, int par) {
for (auto [next, wt] : edges[node]) {
if (next != par && !visited[next]) {
dep[next] = dep[node] + 1;
val[next] = min(val[node] + wt, k + 5);
dfs_val(next, node);
}
}
};
function<void(int, int, int)> dfs_add = [&] (int node, int par, int x) {
if (x == 1) {
at[val[node]].insert(dep[node]);
} else if (x == -1) {
assert(at[val[node]].count(dep[node]));
at[val[node]].erase(at[val[node]].find(dep[node]));
} else if (x == 2) {
if (K - val[node] >= 0 && at[K - val[node]].size()) {
ans = min(ans, dep[node] + *at[K - val[node]].begin());
}
}
for (auto [next, wt] : edges[node]) {
if (next != par && !visited[next]) {
dfs_add(next, node, x);
}
}
};
function<void(int, int)> dfs = [&] (int node, int par) {
dfs_sz(node, par);
int cent = centroid(node, par, sz[node]);
visited[cent] = true;
dep[cent] = val[cent] = 0;
dfs_val(cent, -1);
for (auto [next, wt] : edges[cent]) {
if (!visited[next]) {
dfs_add(next, cent, 1);
}
}
for (auto [next, wt] : edges[cent]) {
if (!visited[next]) {
dfs_add(next, cent, -1);
dfs_add(next, cent, 2);
dfs_add(next, cent, 1);
}
}
for (auto [next, wt] : edges[cent]) {
if (!visited[next]) {
dfs_add(next, cent, -1);
}
}
for (auto [next, wt] : edges[cent]) {
if (!visited[next]) {
dfs(next, cent);
}
}
};
dfs(0, -1);
return (ans == 1e9 ? -1 : ans);
}