# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
888399 | vjudge1 | 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;
using LL = long long;
using PII = pair<int, int>;
const int N = 1e6 + 7;
const LL INF = 1e18;
int n, k;
vector<PII> adj[N];
int sz[N];
LL ans = 0;
bool vis[N];
map<LL, LL> best;
int dfs(int u, int p = 0) {
sz[u] = 1;
for (auto [v, w] : adj[u])
if (!vis[v] && v != p) sz[u] += dfs(v, u);
return sz[u];
}
int centroid(int u, int p, int mx) {
for (auto [v, w] : adj[u])
if (!vis[v] && v != p && sz[v] * 2 > mx) return centroid(v, u, mx);
return u;
}
void go(int u, int p, int depth, int level, bool filling) {
if (filling) {
if (best.count(depth)) best[depth] = min(best[depth], 1LL*level);
else best[depth] = level;
} else {
if (best.count(k-depth)) {
ans = min(ans, best[k - depth] + level);
}
}
for (auto [v, w] : adj[u])
if (!vis[v] && v != p) go(v, u, depth + w, level + 1 ,filling);
}
void decompose(int u) {
int mx = dfs(u, u);
int c = centroid(u, u, mx);
vis[c] = true;
best[0] = 0;
for (auto [v, w] : adj[c]) {
if (!vis[v]) {
go(v, c, w, 1, false);
go(v, c, w, 1, true);
}
}
best.clear();
for (auto[v,w] : adj[c])
if (!vis[v]) decompose(v);
}
int best_paht(int n, int k, int h[][2], int l[]) {
::n = n; ::k = k;
for(int i=0; i<n-1; i++){
int u = h[i][0];
int v = h[i][0];
int w = l[i];
adj[u].emplace_back(v,w);
adj[v].emplace_back(u,w);
}
for (int i = 1; i <= n; i++) best[i] = INF;
ans = INF;
decompose(1);
if(ans > INF/4) ans = -1;
return ans;
}