#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 + 7;
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 = 1; i <= min(k, sz[u]); i++) pref[i][0] = pref[i][1] = inf;
pref[0][0] = pref[0][1] = pref[1][0] = pref[1][1] = 0;
for (auto v : g[u])
{
if (v.fi == par) continue;
combine(u, v.fi, v.se);
}
dp[u][0][0] = dp[u][0][1] = 0;
dp[u][1][0] = dp[u][1][1] = 0;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
//freopen("name.inp","r",stdin);
//freopen("name.out","w",stdout);
cin >> n >> k >> x;
for (int i = 1; i < n; i++)
{
int u, v, c;
cin >> u >> v >> c;
g[u].push_back({v, c});
g[v].push_back({u, c});
}
memset(dp, 0x3f, sizeof dp);
dfs(x, -1);
// for (int i = 1; i <= n; i++)
// {
// cerr << dp[i][k][0] << " " << dp[i][k][1] << "\n";
// }
cout << dp[x][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... |