# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1231136 | domi | Race (IOI11_race) | C++20 | 0 ms | 0 KiB |
#include <bits/stdc++.h>
#include "race.h"
#define int long long
#define fi first
#define se second
#define sz(a) (int)((a).size())
#define all(a) (a).begin(), (a).end()
#define lsb(x) (x & (-x))
#define vi vector<int>
#define YES { cout << "YES" << endl; return; }
#define NO { cout << "NO" << endl; return; }
using ll = long long;
using pii = std::pair<int, int>;
const int NMAX = 2e5;
const int KMAX = 1e6;
using namespace std;
vector<pii> T[NMAX + 5];
int sz[NMAX + 5], used[NMAX + 5], best[KMAX + 5], n, k, ans;
void prec_sz(int nod, int p = -1) {
sz[nod] = 1;
for (auto &[son, cost] : T[nod]) {
if (son == p || used[son]) continue;
prec_sz(son, nod);
sz[nod] += sz[son];
}
}
int get_centroid(int nod, int p, int total) {
for (auto &[son, cost] : T[nod]) {
if (son == p || used[son]) continue;
if (sz[son] > total / 2)
return get_centroid(son, nod, total);
}
return nod;
}
void update(int nod, int p, int sum, int depth) {
if (sum > k) return;
best[sum] = min(best[sum], depth);
for (auto &[son, cost] : T[nod]) {
if (son == p || used[son]) continue;
update(son, nod, sum + cost, depth + 1);
}
}
void remove(int nod, int p, int sum, int depth) {
if (sum > k) return;
best[sum] = LLONG_MAX;
for (auto &[son, cost] : T[nod]) {
if (son == p || used[son]) continue;
remove(son, nod, sum + cost, depth + 1);
}
}
void query(int nod, int p, int sum, int depth) {
if (sum > k) return;
if (best[k - sum] != LLONG_MAX)
ans = min(ans, best[k - sum] + depth);
for (auto &[son, cost] : T[nod]) {
if (son == p || used[son]) continue;
query(son, nod, sum + cost, depth + 1);
}
}
void solve(int nod) {
prec_sz(nod);
int centroid = get_centroid(nod, -1, sz[nod]);
used[centroid] = true;
best[0] = 0;
for (auto &[son, cost] : T[centroid]) {
if (used[son]) continue;
query(son, centroid, cost, 1);
update(son, centroid, cost, 1);
}
for (auto &[son, cost] : T[centroid]) {
if (used[son]) continue;
remove(son, centroid, cost, 1);
}
for (auto &[son, cost] : T[centroid]) {
if (!used[son])
solve(son);
}
}
int best_path(int N, int K, int H[][2], int L[]) {
n = N, k = K;
ans = LLONG_MAX;
for (int i = 0; i < n; i++) {
T[i].clear();
used[i] = 0;
}
for (int i = 0; i <= k; i++) best[i] = LLONG_MAX;
for (int i = 0; i < n - 1; i++) {
int u = H[i][0], v = H[i][1], w = L[i];
T[u].emplace_back(v, w);
T[v].emplace_back(u, w);
}
solve(0);
return (ans == LLONG_MAX ? -1 : ans);
}
// signed main() {
// cin.tie(nullptr)->sync_with_stdio(false);
//
// int N, K;
// cin >> N >> K;
//
// int H[NMAX][2];
// int L[NMAX];
//
// for (int i = 0; i < N - 1; i++) {
// cin >> H[i][0] >> H[i][1] >> L[i];
// }
//
// int answer = best_path(N, K, H, L);
// cout << answer << '\n';
//
// return 0;
// }