# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
746170 | 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 int long long
#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<int, int>;
using ti3 = tuple<int, int, int>;
const int MAX = 200010, INF = (int) 1e9 + 7;
int n, k, sz[MAX], cPar[MAX], visited[MAX], ans = INF;
vector<pii> g[MAX];
map<int, int> mp;
int getSize(int cur, int 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];
}
int getCentroid(int cur, int p, int 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(int cur, int p, int length, int 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(int cur, int p) {
int 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);
}
}
}
signed main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
int a, b, w;
cin >> n >> k;
for (int 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;
}