#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 5;
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx,bmi,bmi2,lzcnt,popcnt")
int dp[2][maxn][maxn], dep[maxn], tmp[2][maxn];
vector<pair<int, int> > G[maxn];
int n, k, r, sub[maxn];
void dfs(int u, int p) {
sub[u] = 1;
dp[0][u][0] = 0;
dp[0][u][1] = 0;
dp[1][u][1] = -dep[u];
for(auto [v, w] : G[u]) {
if(v == p) continue;
dep[v] = dep[u] + w;
dfs(v, u);
sub[u] += sub[v];
}
for(auto [v, w] : G[u]) {
if(v == p) continue;
for(int i=0; i<=min(k, sub[u]); i++) {
tmp[0][i] = dp[0][u][i];
tmp[1][i] = dp[1][u][i];
}
for(int i=1; i<=min(k, sub[u]); i++) {
for(int j=1; i+j<=min(k, sub[u])&&j<=min(k, sub[v]); j++) {
tmp[0][i+j] = min(tmp[0][i+j], dp[0][u][i] + dp[0][v][j] + 2 * w);
tmp[1][i+j] = min(tmp[1][i+j], dp[1][u][i] + dp[0][v][j] + 2 * w);
tmp[1][i+j] = min(tmp[1][i+j], dp[0][u][i] + dp[1][v][j] + 2 * w);
}
}
for(int i=1; i<=min(k, sub[u]); i++) {
dp[0][u][i] = tmp[0][i];
dp[1][u][i] = tmp[1][i];
}
}
}
signed main() {
ios_base::sync_with_stdio(false);
cout.tie(0); cin.tie(0);
cin >> n >> k >> r;
for(int i=1; i<n; i++) {
int a, b, w; cin >> a >> b >> w;
G[a].push_back({ b, w });
G[b].push_back({ a, w });
}
for(int i=1; i<=n; i++)
for(int j=0; j<=k; j++)
for(int k=0; k<2; k++) dp[k][i][j] = 1e9;
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... |