# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1236023 | htoshiro | 경주 (Race) (IOI11_race) | C++20 | 0 ms | 0 KiB |
#include <bits/stdc++.h>
#define int long long
#pragma GCC optimize("Ofast,unroll-loops")
using namespace std;
struct pi {
int x, y;
};
vector<vector<pi>> adj;
vector<int> sz;
vector<bool> blocked;
vector<int> nxt;
int n, k;
int ans;
int dfs(int cur, int par) {
sz[cur] = 1;
for (auto &a : adj[cur]) {
if (a.x != par && !blocked[a.x]) {
sz[cur] += dfs(a.x, cur);
}
}
return sz[cur];
}
int cent(int cur, int par, int am) {
for (auto &a : adj[cur]) {
if (a.x != par && !blocked[a.x] && sz[a.x] > am / 2) {
return cent(a.x, cur, am);
}
}
return cur;
}
void dfs2(int cur, int par, int dist, int depth, vector<pair<int, int>> &paths) {
if (dist > k) return;
paths.emplace_back(dist, depth);
for (auto &a : adj[cur]) {
if (a.x != par && !blocked[a.x]) {
dfs2(a.x, cur, dist + a.y, depth + 1, paths);
}
}
}
int build(int cur, int par) {
int total = dfs(cur, -1);
int curc = cent(cur, -1, total);
blocked[curc] = true;
nxt[curc] = par;
unordered_map<int, int> dist_count;
dist_count[0] = 0;
int best = LLONG_MAX;
for (auto &a : adj[curc]) {
if (!blocked[a.x]) {
vector<pair<int, int>> paths;
dfs2(a.x, curc, a.y, 1, paths);
for (auto &[d, l] : paths) {
if (dist_count.count(k - d)) {
best = min(best, l + dist_count[k - d]);
}
}
for (auto &[d, l] : paths) {
if (!dist_count.count(d)) dist_count[d] = l;
else dist_count[d] = min(dist_count[d], l);
}
}
}
for (auto &a : adj[curc]) {
if (!blocked[a.x]) {
best = min(best, build(a.x, curc));
}
}
return best;
}
int best_path(int N, int K, int H[][2], int L[]){
n = N;
k = K;
adj.resize(n);
sz.resize(n);
nxt.resize(n);
blocked.assign(N, false);
for (int i = 0; i < N-1; i++) {
adj[H[i][0]].push_back({H[i][1], L[i]});
adj[H[i][1]].push_back({H[i][0], L[i]});
}
ans = build(0, -1);
return (ans == LLONG_MAX ? -1 : ans);
}