#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pl = pair<ll,ll>;
using pii = pair<int,int>;
using tpl = tuple<int,int,int>;
#define all(a) a.begin(), a.end()
#define filter(a) a.erase(unique(all(a)), a.end())
const int mn = 1e4 + 1;
int dp[2][mn][mn], knap[2][mn], sz[mn], n, k, x;
vector<pii> adj[mn];
void dfs (int u, int p) {
sz[u] = 1;
for (auto [v, w] : adj[u])
if (v != p) dfs(v, u), sz[u] += sz[v];
knap[0][0] = knap[1][0] = 0;
for (int i = 1; i <= sz[u]; i++)
knap[0][i] = knap[1][i] = INT_MAX;
int knapSize = 0;
for (auto [v, w] : adj[u]) {
if (v == p) continue;
for (int preTake = knapSize; preTake >= 0; preTake--) {
for (int curTake = 1; curTake <= sz[v]; curTake++) {
int sum = preTake + curTake;
knap[0][sum] = min(knap[0][sum], knap[0][preTake] + dp[0][v][curTake] + 2 * w);
knap[1][sum] = min(knap[1][sum], knap[0][preTake] + dp[1][v][curTake] + w);
knap[1][sum] = min(knap[1][sum], knap[1][preTake] + dp[0][v][curTake] + 2 * w);
}
}
knapSize += sz[v];
}
for (int i = 0; i < sz[u]; i++)
dp[0][u][i + 1] = knap[0][i], dp[1][u][i + 1] = knap[1][i];
// cout << "dp " << u << " with size " << sz[u] << ":" << endl;
// for (int i = 1; i <= sz[u]; i++) cout << "size " << i << ": " << dp[0][u][i] << " " << dp[1][u][i] << endl;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n, k, x; cin >> n >> k >> x;
for (int i = 1; i < n; i++) {
int a, b, c; cin >> a >> b >> c;
adj[a].emplace_back(b, c);
adj[b].emplace_back(a, c);
}
dfs(x, -1);
cout << dp[1][x][k] << "\n";
return 0;
}
| # | 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... |