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"
#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 cnt;
pair<int, int> vals[200200];
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 sz[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 flood(int v, int p) {
vals[cnt++] = {dist[v], distw[v]};
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (u != p && !delt[u]) {
flood(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);
int tot = sz[v];
v = centroid(v, -1, v);
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (sz[u] > sz[v]) sz[u] = tot - sz[v];
assert(2 * sz[u] < tot);
}
prepare(v, -1, 0, 0);
best[0] = 0;
for (auto e : adj[v]) {
int u, w; tie(u, w) = e;
if (!delt[u]) {
cnt = 0;
flood(u, v);
for (int z = 0; z < cnt; ++z) if (vals[z].second <= K) ans = min(ans, vals[z].first + best[K - vals[z].second]);
for (int z = 0; z < cnt; ++z) if (vals[z].second <= K) best[vals[z].second] = min(best[vals[z].second], vals[z].first);
}
}
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]].push_back({H[i][1], L[i]});
adj[H[i][1]].push_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
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |