# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1042380 | VectorLi | 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 long long long
using namespace std;
const int N = (int) 2E5;
int n;
int p[N], d[N];
long s[N];
vector<pair<int, long>> e[N];
void DFS1(int u) {
for (auto [v, w] : e[u]) {
if (v != p[u]) {
p[v] = u;
d[v] = d[u] + 1;
s[v] = s[u] + w;
DFS1(v);
}
}
}
long k;
map<long, int> m[N];
int c;
void DFS2(int u) {
m[u][s[u]] = d[u];
for (auto [v, w] : e[u]) {
if (v != p[u]) {
DFS2(v);
if (m[u].size() < m[v].size()) {
swap(m[u], m[v]);
}
for (auto [x, y] : m[v]) {
if (m[u].find(k + s[u] * 2 - x) != m[u].end()) {
c = min(c, y + m[u][k + s[u] * 2 - x] - d[u] * 2);
}
}
for (auto [x, y] : m[v]) {
if (m[u].find(x) != m[u].end()) {
m[u][x] = min(m[u][x], y);
} else {
m[u][x] = y;
}
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> k;
for (int i = 0; i < n - 1; i++) {
int u, v;
long w;
cin >> u >> v >> w;
e[u].push_back({v, w});
e[v].push_back({u, w});
}
p[0] = -1;
DFS1(0);
c = numeric_limits<int>::max();
DFS2(0);
if (c < numeric_limits<int>::max()) {
cout << c << "\n";
} else {
cout << -1 << "\n";
}
return 0;
}