# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1194090 | SpyrosAliv | Race (IOI11_race) | C++20 | 0 ms | 0 KiB |
#include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<vector<pair<int, int>>> tree;
vector<int> sub;
vector<bool> del;
int n, k;
int ans = -1;
vector<int> cnt;
void calc_subs(int node, int par) {
sub[node] = 1;
for (auto [next, w]: tree[node]) {
if (del[next] || next == par) continue;
calc_subs(next, node);
sub[node] += sub[next];
}
}
int find_centroid(int node, int tot, int par = 0) {
for (auto [next, w]: tree[node]) {
if (del[next] || next == par) continue;
if (sub[next] * 2 >= tot) return find_centroid(next, tot, node);
}
return node;
}
void add(int node, int par, ll totLen, int dep = 1, int v) {
if (totLen > k) return;
if (!cnt[totLen]) {
cnt[totLen] = dep;
}
else cnt[totLen] = min(cnt[totLen], dep);
if (v == 0) cnt[totLen] = 0;
for (auto [next, w]: tree[node]) {
if (next == par || del[next]) continue;
add(next, node, totLen + w, dep+1);
}
}
void find_ans(int node, int par, ll totLen, int dep = 1) {
if (totLen > k) return;
ll need = k - totLen;
if (need == 0) {
if (ans == -1) ans = dep;
else ans = min(ans, dep);
}
if (need > 0 && cnt[need]) {
if (ans == -1) ans = cnt[need] + dep;
else ans = min(ans, cnt[need] + dep);
}
for (auto [next, w]: tree[node]) {
if (next == par || del[next]) continue;
find_ans(next, node, totLen + w, dep+1);
}
}
void build(int node) {
calc_subs(node, 0);
int cd = find_centroid(node, sub[node]);
cnt.clear();
for (auto [next, w]: tree[cd]) {
if (del[next]) continue;
find_ans(next, cd, w);
add(next, cd, w, 1);
}
cnt.clear();
del[cd] = true;
for (auto [next, w]: tree[cd]) {
if (del[next]) continue;
add(next, cd, w, 0);
}
for (auto [next, w]: tree[cd]) {
if (del[next]) continue;
build(next);
}
}
int best_path(int N, int K, int H[][2], int L[]) {
n = N;
k = K;
tree.resize(n+1);
del.assign(n+1, false);
sub.assign(n+1, 0);
for (int i = 0; i < n-1; i++) {
H[i][0]++;
H[i][1]++;
tree[H[i][0]].push_back({H[i][1], L[i]});
tree[H[i][1]].push_back({H[i][0], L[i]});
}
cnt.assign(k+1, 0);
build(1);
return ans;
}
/*
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k; cin >> n >> k;
int H[n-1][2], L[n];
for (int i = 0; i < n-1; i++) {
cin >> H[i][0] >> H[i][1] >> L[i];
}
cout << best_path(n, k, H, L) << "\n";
}*/