# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
502089 | mbfibat | 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;
typedef pair<int, int> ii;
vector<ii> adj[200001];
int h[200001], d[200001];
map<int, int> mp[200001];
int dfs(int u, int p, int k) {
int ans = 1e9;
mp[u][d[u]] = h[u];
for (auto& [v, w] : adj[u]) {
if (v == p) continue;
h[v] = h[u] + 1;
d[v] = d[u] + w;
ans = min(ans, dfs(v, u, k));
if (mp[v].size() > mp[u].size()) swap(mp[v], mp[u]);
for (auto& [dis, height] : mp[v])
if (mp[u].count(k - (dis - d[u]) + d[u]))
ans = min(ans, mp[u][k - (dis - d[u]) + d[u]] + height - 2 * h[u]);
for (auto& [dis, height] : mp[v]) {
if (!mp[u].count(dis)) mp[u][dis] = height;
else mp[u][dis] = min(mp[u][dis], height);
}
mp[v].clear();
}
return ans;
}
int best_path(int n, int k, int **h, int *l) {
for (int i = 0; i < n - 1; i++) {
int u = h[i][0], v = h[i][1], w = l[i];
adj[u].push_back(ii(v, w));
adj[v].push_back(ii(u, w));
}
int ans = dfs(0, -1, k);
if (ans == 1e9) ans = -1;
return ans;
}
int main(int argc, char** argv) {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, k; cin >> n >> k;
int **h = new int*[n - 1];
for (int i = 0; i < n - 1; i++) {
h[i] = new int[2];
for (int j = 0; j < 2; j++)
cin >> h[i][j];
}
int *l = new int[n - 1];
for (int i = 0; i < n - 1; i++)
cin >> l[i];
cout << best_path(n, k, h, l);
}