# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
746172 | JooDdae | 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 ll long long
#define double long double
#define fi first
#define se second
#define all(a) (a).begin(), (a).end()
using namespace std;
using pii = pair<int, int>;
using ti3 = tuple<int, int, int>;
const int MAX = 200010, INF = (int) 1e9 + 7;
int n, k, sz[MAX], cPar[MAX], visited[MAX], ans = INF;
vector<pii> g[MAX];
map<int, int> mp;
int getSize(int cur, int p) {
sz[cur] = 1;
for (pii nxt: g[cur]) {
if (nxt.fi != p && !visited[nxt.fi]) sz[cur] += getSize(nxt.fi, cur);
}
return sz[cur];
}
int getCentroid(int cur, int p, int cap) {
for (pii nxt: g[cur]) {
if (nxt.fi != p && !visited[nxt.fi] && sz[nxt.fi] * 2 > cap) {
return getCentroid(nxt.fi, cur, cap);
}
}
return cur;
}
void dfs(int cur, int p, int length, int edgeCnt) {
if (mp.find(k - length) != mp.end()) ans = min(ans, mp[k - length] + edgeCnt);
if (mp.find(length) == mp.end()) mp.insert({ length, edgeCnt });
mp[length] = min(mp[length], edgeCnt);
for (pii nxt: g[cur]) {
if (nxt.fi != p && !visited[nxt.fi]) {
dfs(nxt.fi, cur, length + nxt.se, edgeCnt + 1);
}
}
}
void buildTree(int cur, int p) {
int ctr = getCentroid(cur, -1, getSize(cur, -1));
mp.clear(); mp.insert({ 0, 0 });
dfs(ctr, -1, 0, 0);
cPar[ctr] = p, visited[ctr] = true;
for (pii nxt: g[ctr]) {
if (!visited[nxt.fi]) {
buildTree(nxt.fi, ctr);
}
}
}
int best_path(int N, int K, int H[][2], int L[])
{
int a, b, w;
n = N, k = K;
for (int i = 0; i < n; i++) {
a = H[i][0], b = H[i][1], w = L[i];
g[a].push_back({ b, w }); g[b].push_back({ a, w });
}
buildTree(0, -1);
if (ans == INF) ans = -1;
return ans;
}