#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define pii pair<int, int>
#define pll pair<ll, ll>
#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];
pll dp[Nmax][Nmax];
pll pref[Nmax];
int sz[Nmax];
void combine(int u, int v, int c)
{
for (int i = 1; i <= sz[u]; i++)
{
for (int j = 1; j <= sz[v]; j++)
{
if (i + j > sz[u]) break;
pll val = pref[i];
val.fi += dp[v][j].fi + 2 * c;
val.se = max(val.se, dp[v][j].se + c);
// cerr << val.fi << " " << val.se << "\n";
if (dp[u][i + j].fi - dp[u][i + j].se > val.fi - val.se) dp[u][i + j] = val;
else if (dp[u][i + j].fi - dp[u][i + j].se == val.fi - val.se)
{
if (dp[u][i + j].fi > val.fi) dp[u][i + j] = val;
}
}
}
for (int i = 1; i <= sz[u]; i++)
{
if (pref[i].fi - pref[i].se > dp[u][i].fi - dp[u][i].se) pref[i] = dp[u][i];
// cerr << dp[u][i].fi << " " << dp[u][i].se << "\n";
}
}
void dfs(int u, int p)
{
sz[u] = 1;
for (auto v : g[u])
{
if (v.fi == p) continue;
dfs(v.fi, u);
sz[u] += sz[v.fi];
}
for (int i = 0; i <= sz[u]; i++) pref[i] = {1LL * inf * inf, -1LL * inf * inf};
pref[1] = {0, 0};
for (auto v : g[u])
{
if (v.fi == p) continue;
combine(u, v.fi, v.se);
}
dp[u][0] = {0, 0};
dp[u][1] = {0, 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});
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = {1LL * inf * inf, -1LL * inf * inf};
dfs(x, -1);
// for (int i = 0; i <= 10; i++) cerr << dp[7][i].fi << " " << dp[7][i].se << "\n";
// ll res = 8 * 1LL * inf * inf;
// for (int i = 1; i <= n; i++)
// {
// res = min(res, dp[i][k].fi - dp[i][k].se);
//// cerr << dp[i][k].fi << " " << dp[i][k].se << "\n";
// }
// cout << res << "\n";
cout << dp[x][k].fi - dp[x][k].se << "\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... |