# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
746171 | kongum | 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>
#define ll long long
#define double long double
#define fi first
#define se second
#define all(a) (a).begin(), (a).end()
using namespace std;
using pii = pair<ll, ll>;
using ti3 = tuple<ll, ll, ll>;
const ll MAX = 200010, INF = (ll) 1e9 + 7;
ll n, k, sz[MAX], cPar[MAX], visited[MAX], ans = INF;
vector<pii> g[MAX];
map<ll, ll> mp;
ll getSize(ll cur, ll p) {
sz[cur] = 1;
for (pii nxt: g[cur]) {
if (nxt.fi != p && !visited[nxt.fi]) sz[cur] += getSize(nxt.fi, cur);
}
return sz[cur];
}
ll getCentroid(ll cur, ll p, ll cap) {
for (pii nxt: g[cur]) {
if (nxt.fi != p && !visited[nxt.fi] && sz[nxt.fi] * 2 > cap) {
return getCentroid(nxt.fi, cur, cap);
}
}
return cur;
}
void dfs(ll cur, ll p, ll length, ll edgeCnt) {
if (mp.find(k - length) != mp.end()) ans = min(ans, mp[k - length] + edgeCnt);
if (mp.find(length) == mp.end()) mp.insert({ length, edgeCnt });
mp[length] = min(mp[length], edgeCnt);
for (pii nxt: g[cur]) {
if (nxt.fi != p && !visited[nxt.fi]) {
dfs(nxt.fi, cur, length + nxt.se, edgeCnt + 1);
}
}
}
void buildTree(ll cur, ll p) {
ll ctr = getCentroid(cur, -1, getSize(cur, -1));
mp.clear(); mp.insert({ 0, 0 });
dfs(ctr, -1, 0, 0);
cPar[ctr] = p, visited[ctr] = true;
for (pii nxt: g[ctr]) {
if (!visited[nxt.fi]) {
buildTree(nxt.fi, ctr);
}
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
ll a, b, w;
cin >> n >> k;
for (ll i = 0; i < n; i++) {
cin >> a >> b >> w;
g[a].push_back({ b, w }); g[b].push_back({ a, w });
}
buildTree(0, -1);
if (ans == INF) ans = -1;
cout << ans;
}