# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1119866 | btninh | 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>
#define int long long
#define N 100005
#define pb push_back
#define INF 1e18
using namespace std;
int sz[N], ans = INF, k;
bool vis[N];
map<int, int> cnt;
vector<pair<int, int>> g[N];
int dfs(int u, int p = -1) {
sz[u] = 1;
for (auto [v, w] : g[u]) {
if (v != p && !vis[v]) {
sz[u] += dfs(v, u);
}
}
return sz[u];
}
int centroid(int u, int p, int len) {
for (auto [v, w] : g[u]) {
if (v != p && !vis[v] && sz[v] > len / 2) {
return centroid(v, u, len);
}
}
return u;
}
void calc(int u, int p, bool t, int sum, int d = 1) {
if (t == 0) {
if (!cnt[sum])
cnt[sum] = d;
else
cnt[sum] = min(cnt[sum], d);
} else {
if (cnt[k - sum])
ans = min(ans, d + cnt[k - sum]);
}
for (auto [v, w] : g[u]) {
if (v != p && !vis[v]) {
calc(v, u, t, sum + w, d + 1);
}
}
}
void solve(int u) {
int c = centroid(u, -1, dfs(u));
vis[c] = true;
cnt.clear();
cnt[0] = 0;
for (auto [v, w] : g[c]) {
if (!vis[v]) {
calc(v, c, 1, w);
calc(v, c, 0, w);
}
}
for (auto [v, w] : g[c]) {
if (!vis[v]) solve(v);
}
}
void best_path(int n, int K, int roads[][2], int lengths[]) {
k = K;
for (int i = 0; i < n - 1; ++i) {
int u = roads[i][0] + 1, v = roads[i][1] + 1;
int l = lengths[i];
g[u].pb({v, l});
g[v].pb({u, l});
}
ans = INF;
solve(1);
cout << (ans != INF ? ans : -1) << "\n";
}