# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
887228 | amsraman | 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>
using namespace std;
int best_path(int n, int k, vector<vector<int>> h, vector<int> l) {
int ans = n + 1;
vector<int> sz(n); vector<bool> vis(n, false);
vector<vector<pair<int, int>>> g(n);
for(int i = 0; i < n - 1; i++) {
g[h[i][0]].emplace_back(h[i][1], l[i]);
g[h[i][1]].emplace_back(h[i][0], l[i]);
}
map<int, int> m1, m2;
auto proc = [&](auto rec, int u, int p, int num, int sum) -> void {
if(!m2.count(sum)) m2[sum] = num;
else m2[sum] = min(m2[sum], num);
for(auto [v, w]: g[u]) {
if(v == p || vis[v]) continue;
rec(rec, v, u, num + 1, sum + w);
}
};
auto get_size = [&](auto rec, int u, int p = 0) -> int {
sz[u] = 1;
for(auto [v, w]: g[u]) {
if(v != p && !vis[v]) {
sz[u] += rec(rec, v, u);
}
}
return sz[u];
};
auto find_centroid = [&](auto rec, int u, int p, int full_sz) -> int {
for(auto [v, w]: g[u]) {
if(v != p && !vis[v] && 2 * sz[v] > full_sz) {
return rec(rec, v, u, full_sz);
}
}
return u;
};
auto centroid_decomp = [&](auto rec, int u) -> void {
get_size(get_size, u, u);
u = find_centroid(find_centroid, u, u, sz[u]);
get_size(get_size, u, u);
vis[u] = true;
m1[0] = 0;
for(auto [v, w]: g[u]) {
if(!vis[v]) {
proc(proc, v, v, 1, w);
for(auto [sum, num]: m2) {
if(m1.count(k - sum)) {
ans = min(ans, num + m1[k - sum]);
}
}
for(auto [sum, num]: m2) {
if(!m1.count(sum)) m1[sum] = num;
else m1[sum] = min(m1[sum], num);
}
m2.clear();
}
}
m1.clear();
for(auto [v, w]: g[u]) {
if(!vis[v]) rec(rec, v);
}
};
centroid_decomp(centroid_decomp, 0);
return ans == n + 1 ? -1 : ans;
}