# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
1231150 | domi | 경주 (Race) (IOI11_race) | C++20 | 0 ms | 0 KiB |
#include <bits/stdc++.h>
#include "race.h"
#define int64_t long long
#define fi first
#define se second
#define sz(a) (int64_t)((a).size())
#define all(a) (a).begin(), (a).end()
#define lsb(x) (x & (-x))
#define vi vector<int64_t>
#define YES { cout << "YES" << endl; return; }
#define NO { cout << "NO" << endl; return; }
using ll = long long;
using pii = std::pair<int64_t, int64_t>;
const int64_t NMAX = 2e5;
const int64_t KMAX = 1e6;
using namespace std;
vector<pii> T[NMAX + 5];
int64_t sz[NMAX + 5], used[NMAX + 5], best[KMAX + 5], n, k, ans;
void prec_sz(int64_t nod, int64_t 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];
}
}
int64_t get_centroid(int64_t nod, int64_t p, int64_t 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(int64_t nod, int64_t p, int64_t sum, int64_t 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(int64_t nod, int64_t p, int64_t sum, int64_t 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(int64_t nod, int64_t p, int64_t sum, int64_t 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(int64_t nod) {
prec_sz(nod);
int64_t 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);
}
}
int64_t best_path(int64_t N, int64_t K, int64_t H[][2], int64_t L[]) {
n = N, k = K;
ans = LLONG_MAX;
for (int64_t i = 0; i < n; i++) {
T[i].clear();
used[i] = 0;
}
for (int64_t i = 0; i <= k; i++) best[i] = LLONG_MAX;
for (int64_t i = 0; i < n - 1; i++) {
int64_t 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);
//
// int64_t N, K;
// cin >> N >> K;
//
// int64_t H[NMAX][2];
// int64_t L[NMAX];
//
// for (int64_t i = 0; i < N - 1; i++) {
// cin >> H[i][0] >> H[i][1] >> L[i];
// }
//
// int64_t answer = best_path(N, K, H, L);
// cout << answer << '\n';
//
// return 0;
// }