fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define int long long
  5.  
  6. const int N = 5007;
  7. const int inf = 1e16;
  8.  
  9. int n, dp[N][N][2];
  10. vector<pair<int, int>> adj[N];
  11.  
  12. void dfs (int u, int p){
  13. dp[u][1][0] = dp[u][1][1] = 0;
  14. for (pair<int, int> pr : adj[u]){
  15. int v = pr.first, w = pr.second;
  16. if (v != p)
  17. dfs(v, u);
  18. }
  19. for (pair<int, int> pr : adj[u]){
  20. int v = pr.first, w = pr.second;
  21. if (v != p){
  22. for (int i = n; i >= 2; --i)
  23. for (int j = 1; j < i; ++j){
  24. dp[u][i][0] = min(dp[u][i][0], dp[u][i - j][0] + (dp[v][j][0] + w) * 2);
  25. dp[u][i][1] = min(dp[u][i][1], dp[u][i - j][1] + (dp[v][j][0] + w) * 2);
  26. dp[u][i][1] = min(dp[u][i][1], dp[u][i - j][0] + dp[v][j][1] + w);
  27. }
  28. }
  29. }
  30. }
  31.  
  32. int32_t main (){
  33. ios::sync_with_stdio(false); cin.tie(nullptr);
  34. freopen("migration.inp", "r", stdin);
  35. freopen("migration.out", "w", stdout);
  36. cin >> n;
  37. for (int i = 1; i <= n; ++i)
  38. for (int j = 1; j <= n; ++j){
  39. dp[i][j][0] = inf;
  40. dp[i][j][1] = inf;
  41. }
  42. for (int i = 1; i < n; ++i){
  43. int u, v, w; cin >> u >> v >> w;
  44. adj[u].push_back({v, w});
  45. adj[v].push_back({u, w});
  46. }
  47. dfs(1, 0);
  48. for (int i = 1; i <= n; ++i)
  49. cout << dp[1][i][1] << "\n";
  50. }
  51.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
Standard output is empty