#include <bits/stdc++.h>
using namespace std;
const int M = 1e4 + 5;
int dp[2][M][M], dep[M];
vector<pair<int, int> > G[M];
int n, k, r, S[M], a, b, w;
void dfs(int u, int p) {
S[u] = 1;
for(auto [v, w] : G[u]) {
if(v == p) continue;
dep[v] = dep[u] + w;
dfs(v, u);
S[u] += S[v];
}
for(int i=0; i<=S[u]; i++)
dp[0][u][i] = dp[1][u][i] = 1e9;
dp[0][u][0] = 0;
dp[0][u][1] = 0;
dp[1][u][1] = -dep[u];
S[u] = 1;
for(auto [v, w] : G[u]) {
if(v == p) continue;
int t = S[u] + S[v];
for(int i=min(t, k); i>=2; i--) {
for(int j=min(S[v], i-1); j>=max(1, i-S[u]); j--) {
dp[0][u][i] = min(dp[0][u][i], dp[0][v][j] + dp[0][u][i-j] + 2 * w);
dp[1][u][i] = min(dp[1][u][i], dp[1][u][i-j] + dp[0][v][j] + 2 * w);
dp[1][u][i] = min(dp[1][u][i], dp[0][u][i-j] + dp[1][v][j] + 2 * w);
}
}
S[u] += S[v];
}
}
int main() {
cin >> n >> k >> r;
for(int i=1; i<n; i++) {
cin >> a >> b >> w;
G[a].push_back({ b, w });
G[b].push_back({ a, w });
}
dfs(r, r);
cout << dp[1][r][k] << '\n';
}
# | 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... |