# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
970000 | Ghetto | Race (IOI11_race) | C++17 | 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.
#include <bits/stdc++.h>
using namespace std;
using lint = long long;
using pil = pair<int, lint>;
using pli = pair<lint, int>;
using mli = unordered_map<lint, int>;
const int MAX_N = 2e5 + 5, INF = 2e9;
int n;
lint k;
vector<pil> adj[MAX_N];
bool del[MAX_N];
int sub_size[MAX_N];
void upd_sizes(int u, int par = -1) {
sub_size[u] = 1;
for (pil x : adj[u]) {
int v = x.first;
if (v == par || del[v]) continue;
upd_sizes(v, u);
sub_size[u] += sub_size[v];
}
}
int find_cent(int u, int tot_size, int par = -1) {
for (pil x : adj[u]) {
int v = x.first;
if (v == par || del[v]) continue;
if (sub_size[v] * 2 > tot_size) return find_cent(v, tot_size, u);
}
return u;
}
mli lens[MAX_N], pref_lens;
void merge(mli& x, mli& y) { // y into x
if (x.size() < y.size()) x.swap(y);
for (pli z : y)
x[z.first] = x.count(z.first) ? min(x[z.first], z.second) : z.second;
}
void upd_lens(int u, int par, lint dist, int depth = 1) {
lens[u].insert({dist, depth});
for (pil x : adj[u]) {
int v = x.first;
if (v == par || del[v]) continue;
upd_lens(v, u, dist + x.second, depth + 1);
merge(lens[u], lens[v]);
}
}
int ans = INF;
void build(int u) {
upd_sizes(u);
int cent = find_cent(u, sub_size[u]);
pref_lens.clear();
for (pil x : adj[cent]) if (!del[x.first]) lens[x.first].clear();
for (pil x : adj[cent]) {
int v = x.first;
if (del[v]) continue;
upd_lens(v, cent, x.second);
for (pli y : lens[v]) {
if (y.first == k) ans = min(ans, y.second);
else if (pref_lens.count(k - y.first)) ans = min(ans, y.second + pref_lens[k - y.first]);
}
merge(pref_lens, lens[v]);
}
del[cent] = true;
for (pil x : adj[cent])
if (!del[x.first]) build(x.first);
}
int main() {
freopen("race.in", "r", stdin);
freopen("race.out", "w", stdout);
cin.sync_with_stdio(false); cin.tie(0);
cin >> n >> k;
for (int i = 1; i < n; i++) {
int u, v; cin >> u >> v;
lint w; cin >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
build(0);
if (ans == INF) ans = -1;
cout << ans << '\n';
}