This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
using pii = pair<int, int>;
template <typename T> void min_self(T &a, T b) { if(b < a) a = b; }
const int N = 10010;
const int inf = (int)1e9;
int dp[N][N];
vector<pii> g[N];
int n, k, x;
// 25 points
int f[N][N][2];
#define come_back 0
#define leave 1
void dfs(int u, int p = -1){
f[u][1][come_back] = f[u][1][leave] = 0;
vector<pii> ch;
for(auto [v, c] : g[u]) if(v != p){
dfs(v, u);
ch.emplace_back(v, c);
}
if(ch.empty()) return ;
if((int)ch.size() == 1){
for(auto [v, c] : ch){
for(int vis = 1;vis < k;vis++){ // k <= 100.
f[u][vis + 1][leave] = c + min(f[v][vis][leave], f[v][vis][come_back]);
f[u][vis + 1][come_back] = 2 * c + f[v][vis][come_back];
}
}
} else if((int)ch.size() == 2){
for(int vis = 1;vis < k;vis++){
for(int vis1 = 0;vis1 <= vis;vis1++){
int vis2 = vis - vis1;
auto [v1, c1] = ch[0];
auto [v2, c2] = ch[1];
c1 = (vis1 > 0 ? c1 : 0);
c2 = (vis2 > 0 ? c2 : 0);
min_self(f[u][vis + 1][come_back], 2 * c1 + 2 * c2 + f[v1][vis1][come_back] + f[v2][vis2][come_back]);
if(c1 > c2){
swap(v1, v2);
swap(c1, c2);
}
min_self(f[u][vis + 1][leave], 2 * c1 + c2 + f[v1][vis1][come_back] + min(f[v2][vis2][leave], f[v2][vis2][come_back]));
}
}
} else {
for(int vis = 1;vis < k;vis++){
for(int vis1 = 0;vis1 <= vis;vis1++){
for(int vis2 = 0;vis2 + vis1 <= vis;vis2++){
int vis3 = vis - vis1 - vis2;
assert(vis1 + vis2 + vis3 == vis);
auto [v1, c1] = ch[0];
auto [v2, c2] = ch[1];
auto [v3, c3] = ch[2];
c1 = (vis1 > 0 ? c1 : 0);
c2 = (vis2 > 0 ? c2 : 0);
c3 = (vis3 > 0 ? c3 : 0);
min_self(f[u][vis + 1][come_back], 2 * (c1 + c2 + c3) + f[v1][vis1][come_back] + f[v2][vis2][come_back] + f[v3][vis3][come_back]);
if(c1 > c2){
swap(v1, v2);
swap(c1, c2);
}
if(c1 > c3){
swap(v1, v3);
swap(c1, c3);
}
if(c2 > c3){
swap(v2, v3);
swap(c2, c3);
}
min_self(f[u][vis + 1][leave], 2 * c1 + 2 * c2 + c3 + f[v1][vis1][come_back] + f[v2][vis2][come_back] + min(f[v3][vis3][leave], f[v3][vis3][come_back]));
}
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
//~ for(int i = 0;i < N;i++) for(int j = 1;j < N;j++) dp[i][j] = inf;
for(int a = 0;a < N;a++) for(int b = 1;b < N;b++) for(int c = 0;c < 2;c++) f[a][b][c] = inf;
cin >> n >> k >> x;
for(int i = 1;i <= n - 1;i++){
int a, b, c;
cin >> a >> b >> c;
g[a].emplace_back(b, c);
g[b].emplace_back(a, c);
}
dfs(x);
cout << min(f[x][k][come_back], f[x][k][leave]) << '\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... |