# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
231900 | IOrtroiii | Race (IOI11_race) | C++14 | 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.
#ifndef KienVu
#include "race.h"
#include "racelib.h"
#endif // KienVu
#include <bits/stdc++.h>
using namespace std;
int N, K;
vector<pair<int, int>> adj[200200];
int dist[200200];
int distw[200200];
int sz[200200];
bool delt[200200];
int best[1000100];
int calc_sz(int v, int p) {
sz[v] = 1;
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (u != p && !delt[u]) {
sz[v] += calc_sz(u, v);
}
}
return v;
}
int centroid(int v, int p, int r) {
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (u != p && !delt[u] && 2 * sz[u] >= sz[r]) {
return centroid(u, v, r);
}
}
return v;
}
void prepare(int v, int p, int d, int dw) {
dw = min(dw, K + 1);
dist[v] = d;
distw[v] = dw;
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (u != p && !delt[u]) {
prepare(u, v, d + 1, dw + w);
}
}
}
int ans = 1e9;
void query(int v, int p) {
if (distw[v] <= K) {
ans = min(ans, dist[v] + best[K - distw[v]]);
}
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (u != p && !delt[u]) {
query(u, v);
}
}
}
void modify(int v, int p) {
if (distw[v] <= K) best[distw[v]] = min(best[distw[v]], dist[v]);
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (u != p && !delt[u]) {
modify(u, v);
}
}
}
void reset(int v, int p) {
if (distw[v] <= K) best[distw[v]] = 1e9;
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (u != p && !delt[u]) {
reset(u, v);
}
}
}
void solve(int v) {
calc_sz(v, -1);
v = centroid(v, -1, v);
prepare(v, -1, 0, 0);
best[0] = 0;
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (!delt[u]) {
query(u, v);
modify(u, v);
}
}
reset(v, -1);
delt[v] = true;
for (auto e : adj[v]) if (!delt[e.first]) solve(e.first);
}
int best_path(int N, int K, int H[][2], int L[]) {
::N = N;
::K = K;
for (int i = 0; i < N - 1; ++i) {
adj[H[i][0]].emplace_back(H[i][1], L[i]);
adj[H[i][1]].emplace_back(H[i][0], L[i]);
}
for (int i = 0; i < 1000100; ++i) best[i] = 1e9;
solve(0);
if (ans > N) ans = -1;
return ans;
}
#ifdef KienVu
int main() {
int N, K;
while (cin >> N >> K) {
int H[N - 1][2], L[N - 1];
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";
}
}
#endif