#include <bits/stdc++.h>
#define ar array
//#define int long long
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
const int mod = 1e9 + 7;
const ll inf = 1e18;
const int maxn = 1e4 + 5;
int dp[maxn][maxn][2], dep[maxn], tmp[maxn][2];
vector<pii> G[maxn];
int n, k, r, sub[maxn];
void dfs(int u, int p) {
sub[u] = 1;
dp[u][0][0] = 0;
dp[u][1][0] = 0;
dp[u][1][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[i][0] = dp[u][i][0];
tmp[i][1] = dp[u][i][1];
}
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[i+j][0] = min(tmp[i+j][0], dp[u][i][0] + dp[v][j][0] + 2 * w);
tmp[i+j][1] = min(tmp[i+j][1], dp[u][i][1] + dp[v][j][0] + 2 * w);
tmp[i+j][1] = min(tmp[i+j][1], dp[u][i][0] + dp[v][j][1] + 2 * w);
}
}
for(int i=1; i<=min(k, sub[u]); i++) {
dp[u][i][0] = tmp[i][0];
dp[u][i][1] = tmp[i][1];
}
}
}
signed main() {
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[i][j][k] = 1e9;
dfs(r, r);
cout << dp[r][k][1] << '\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... |