Fshl0

Untitled

Mar 28th, 2022
966
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define     F       first
  5. #define     S       second
  6. typedef pair<int, int>  pi;
  7. typedef long long       ll;
  8.  
  9. const int MAX=1e5+9;
  10. const ll OO=1e18+18;
  11. int n, k, cntLeafs[MAX];
  12. ll dp[MAX][109], temp[109];
  13. vector<pi> adj[MAX];
  14.  
  15. template<typename T>
  16. void Min(T& a, T b) {
  17.     a=min(a, b);
  18. }
  19.  
  20. void DFS(int cur, int par) {
  21.     dp[cur][0]=0;
  22.     for (int i=1; i<=k; ++i) {
  23.         dp[cur][i]=OO;
  24.     }
  25.  
  26.     if (adj[cur].size()==1) {
  27.         dp[cur][1]=0;
  28.         cntLeafs[cur]=1;
  29.     }
  30.     else {
  31.         cntLeafs[cur]=0;
  32.     }
  33.  
  34.     for (int i=0; i<adj[cur].size(); ++i) {
  35.         int child=adj[cur][i].F,
  36.             cost=adj[cur][i].S;
  37.  
  38.         if (child==par) {
  39.             continue;
  40.         }
  41.  
  42.         DFS(child, cur);
  43.         cntLeafs[cur]+=cntLeafs[child];
  44.  
  45.         for (int i=0; i<=min(cntLeafs[cur], k); ++i) {
  46.             temp[i]=OO;
  47.         }
  48.  
  49.         for (int i=0; i<=min(cntLeafs[child], k); ++i) {
  50.             for (int j=0; j<=cntLeafs[cur] && i+j<=k; ++j) {
  51.                 Min(temp[i+j], dp[child][i]+1LL*(k-i)*i*cost+dp[cur][j]);
  52.             }
  53.         }
  54.  
  55.         for (int i=0; i<=min(cntLeafs[cur], k); ++i) {
  56.             Min(dp[cur][i], temp[i]);
  57.         }
  58.     }
  59. }
  60.  
  61. int main() {
  62.     int t;
  63.     scanf("%d", &t);
  64.     for (int testCase=1; testCase<=t; ++testCase) {
  65.         scanf("%d%d", &n, &k);
  66.         for (int i=1; i<=n; ++i) {
  67.             adj[i].clear();
  68.         }
  69.  
  70.         for (int i=1; i<=n-1; ++i) {
  71.             int x, y, w;
  72.             scanf("%d%d%d", &x, &y, &w);
  73.             adj[x].push_back({y, w});
  74.             adj[y].push_back({x, w});
  75.         }
  76.  
  77.         if (n==2) {
  78.             printf("Case #%d: %d\n", testCase, adj[1][0].S);
  79.         }
  80.         else {
  81.             for (int i=1; i<=n; ++i) {
  82.                 if (adj[i].size()!=1) {
  83.                     DFS(i, -1);
  84.                     printf("Case #%d: %lld\n", testCase, dp[i][k]);
  85.                     break;
  86.                 }
  87.             }
  88.         }
  89.     }
  90.  
  91.     return 0;
  92. }
  93.  
Advertisement
Add Comment
Please, Sign In to add comment