#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;
ll dep[maxn], sub[maxn];
vector<vector<ll> > dp[maxn];
vector<pii> G[maxn];
int n, k, r;
void dfs(int u, int p) {
sub[u] = 1;
for(auto [v, w] : G[u]) {
if(v == p) continue;
dep[v] = dep[u] + w;
dfs(v, u);
sub[u] += sub[v];
}
int m = sub[u];
dp[u].resize(m+1, vector<ll>(2, 1e15));
ll tmp[m+1][2];
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;
for(int i=0; i<=sub[u]; i++) {
tmp[i][0] = dp[u][i][0];
tmp[i][1] = dp[u][i][1];
}
for(int i=1; i<=sub[u]; i++) {
for(int j=1; i+j<=sub[u]&&j<=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=0; i<=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 });
}
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... |