#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define pii pair<int, int>
#define pll pair<ll, ll>
#define mp(x, y) make_pair(x, y)
#define MASK(i) ((1LL) << (i))
#define BIT(x, i) (((x) >> (i)) & 1)
#define fi first
#define se second
using namespace std;
const long inf = 1e9 + 7;
const long mod = 1e9 + 7;
const long Nmax = 1e4 + 1;
const long lg = 20;
const long bs = 1003;
int n, k, x;
vector<pii> g[Nmax];
int dp[Nmax][Nmax][2];
int pref[Nmax][2];
int sz[Nmax];
void combine(int u, int v, int c)
{
for (int i = 1; i <= min(sz[u], k); i++)
{
// dp[u][i][0] = min(dp[u][i][0], pref[i][0]);
// dp[u][i][1] = min(dp[u][i][1], pref[i][1]);
for (int j = 1; j <= min(sz[v], k); j++)
{
if (i + j > min(sz[u],k)) break;
dp[u][i + j][0] = min(dp[u][i + j][0], pref[i][0] + dp[v][j][0] + 2 * c);
dp[u][i + j][1] = min(dp[u][i + j][1], pref[i][1] + dp[v][j][0] + 2 * c);
dp[u][i + j][1] = min(dp[u][i + j][1], pref[i][0] + dp[v][j][1] + c);
}
}
for (int i = 1; i <= min(k, sz[u]); i++)
{
pref[i][0] = min(pref[i][0], dp[u][i][0]);
pref[i][1] = min(pref[i][1], dp[u][i][1]);
}
}
void dfs(int u, int par)
{
sz[u] = 1;
for (auto v : g[u])
{
if (v.fi == par) continue;
dfs(v.fi, u);
sz[u] += sz[v.fi];
}
for (int i = 2; i <= min(sz[u], k); i++) dp[u][i][0] = dp[u][i][1] = pref[i][0] = pref[i][1] = inf;
for (auto v : g[u])
{
if (v.fi == par) continue;
combine(u, v.fi, v.se);
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
//freopen("name.inp","r",stdin);
//freopen("name.out","w",stdout);
int u, v, c;
cin >> n >> k >> x;
for (int i = 1; i < n; i++)
{
cin >> u >> v >> c;
g[u].push_back({v, c});
g[v].push_back({u, c});
}
dfs(x, -1);
cout << dp[x][k][1];
}
# | 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... |