#include <bits/stdc++.h>
#include "race.h"
using namespace std;
vector<vector<pair<int, int>>> g;
vector<map<int, int>> dp;
void dbg(map<int, int> m) {
for (auto [x, y] : m) cerr << x << ' ' << y << '\n';
cerr << '\n';
}
int k, res;
void dfs(int u, int p) {
dp[u][0] = 0;
for (auto [v, w] : g[u]) {
if (v == p) continue;
dfs(v, u);
map<int, int> m;
for (auto [len, x] : dp[v]) {
m[len + w] = x + 1;
}
if (dp[u].size() > m.size()) {
swap(dp[u], m);
}
auto dp_nw = dp[u];
for (auto [len, x] : dp[u]) {
for (auto [s, cost] : m) {
int len_nw = s + len;
if (!dp_nw.count(len_nw)) {
dp_nw[len_nw] = x + cost;
} else {
dp_nw[len_nw] = min(dp_nw[len_nw], x + cost);
}
}
}
swap(dp[u], dp_nw);
dp[v].clear();
}
if (dp[u].count(k)) {
res = min(res, dp[u][k]);
}
}
int best_path(int N, int K, int H[][2], int L[]) {
k = K;
g.resize(N);
dp.resize(N);
for (int i = 0; i < N - 1; i++) {
int u = H[i][0], v = H[i][1], w = L[i];
g[u].push_back({v, w});
g[v].push_back({u, w});
}
res = N + 1;
dfs(0, -1);
return (res == N + 1 ? -1 : res);
}
| # | 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... |