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;
#ifdef tabr
#include "library/debug.cpp"
#else
#define debug(...)
#endif
int best_path(int n, int k, int h[][2], int l[]) {
vector<vector<int>> g(n);
for (int i = 0; i < n - 1; i++) {
g[h[i][0]].emplace_back(i);
g[h[i][1]].emplace_back(i);
}
int ans = n;
vector<int> depth(n);
vector<long long> dist(n);
vector<map<long long, int>> a(n);
function<void(int, int)> dfs = [&](int v, int p) {
vector<int> c;
for (int id : g[v]) {
int to = v ^ h[id][0] ^ h[id][1];
if (to == p) {
continue;
}
c.emplace_back(to);
depth[to] = depth[v] + 1;
dist[to] = dist[v] + l[id];
dfs(to, v);
long long t = dist[v] + k;
if (a[to].count(t)) {
ans = min(ans, a[to][t] - depth[v]);
}
}
if (c.empty()) {
a[v][dist[v]] = depth[v];
return;
}
sort(c.begin(), c.end(), [&](int i, int j) {
return a[i].size() > a[j].size();
});
swap(a[v], a[c[0]]);
for (int i = 1; i < (int) c.size(); i++) {
for (auto q : a[c[i]]) {
long long t = 2 * dist[v] - q.first + k;
if (a[v].count(t)) {
ans = min(ans, a[v][t] + q.second - 2 * depth[v]);
}
if (!a[v].count(q.first)) {
a[v][q.first] = n;
}
a[v][q.first] = min(a[v][q.first], q.second);
}
}
};
dfs(0, -1);
if (ans == n) {
ans = -1;
}
return ans;
}
#ifdef tabr
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k, h[100][2], l[100];
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> h[i][0] >> h[i][1] >> l[i];
}
cout << best_path(n, k, h, l) << '\n';
return 0;
}
#endif
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |