///roadtoVOI2025
///enjoythejourney
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fi first
#define se second
#define ii pair<int,int>
#define mp make_pair
#define in(x) freopen(x,"r",stdin)
#define out(x) freopen(x,"w",stdout)
#define bit(x,i) ((x>>i)&1)
#define lc (id<<1)
#define rc ((id<<1)^1)
const int maxn=1e4+7;
const int inf=1e9+7;
vector<ii>adj[maxn];
int dp[maxn][2][maxn];
int ndp[2][maxn];
int sz[maxn];
int n,k,x;
void work(int u,int v,int w)
{
for(int i=sz[u];i>=0;i--){
for(int j=sz[v];j>=1;j--){
ndp[0][i+j]=min(ndp[0][i+j],dp[u][0][i]+dp[v][0][j]+2*w);
ndp[1][i+j]=min(ndp[1][i+j],dp[u][1][i]+dp[v][0][j]+2*w);
ndp[1][i+j]=min(ndp[1][i+j],dp[u][0][i]+dp[v][1][j]+w);
}
}
sz[u]+=sz[v];
for(int i=sz[u];i>=0;i--){
dp[u][0][i]=min(dp[u][0][i],ndp[0][i]);
dp[u][1][i]=min(dp[u][1][i],ndp[1][i]);
ndp[0][i]=inf;
ndp[1][i]=inf;
}
}
void dfs(int u,int par)
{
sz[u]=1;
dp[u][0][1]=0;
dp[u][1][1]=0;
for(ii pp:adj[u]){
int v=pp.fi;
int w=pp.se;
if(v==par)continue;
dfs(v,u);
work(u,v,w);
}
}
void sol()
{
cin>>n>>k>>x;
ndp[0][0]=inf;
ndp[1][0]=inf;
for(int i=1;i<=n;i++){
ndp[0][i]=inf;
ndp[1][i]=inf;
for(int j=0;j<=n;j++){
dp[i][0][j]=inf;
dp[i][1][j]=inf;
}
}
for(int i=1;i<n;i++){
int u,v,w;
cin>>u>>v>>w;
adj[u].push_back({v,w});
adj[v].push_back({u,w});
}
dfs(x,0);
cout<<min(dp[x][1][k],dp[x][0][k])<<"\n";
}
signed main(void)
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int t=1;
while(t--){
sol();
}
// you should actually read the stuff at the bottom
return 0;
}
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1?)
* do smth instead of nothing and stay organized
* WRITE STUFF DOWN
* DON'T GET STUCK ON ONE APPROACH
*/
# | 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... |