1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
  | // 더 많은 정보는 42jerrykim.github.io 에서 확인하세요.
#include <bits/stdc++.h>
using namespace std;
using int64 = long long;
const int64 NEG_INF = -(1LL<<60);
int N, K;
vector<vector<pair<int,int>>> adj;
vector<int64> dfs(int u, int parent) {
    // dp[t] = max contribution within subtree of u when exactly t nodes are chosen in this subtree
    vector<int64> dp(1, 0); // t = 0
    int currentCap = 0;     // current max t index available in dp
    for (auto [v, w] : adj[u]) {
        if (v == parent) continue;
        vector<int64> child = dfs(v, u);
        // child's contribution + edge(u-v) contribution for selecting t in v-subtree
        int childCap = (int)child.size() - 1;
        vector<int64> bestChild(childCap + 1, NEG_INF);
        for (int t = 0; t <= childCap; ++t) {
            int m = min(t, (K + 1) - t);
            bestChild[t] = child[t] + 1LL * w * m;
        }
        // knapsack merge dp with bestChild
        int newCap = min(K, currentCap + childCap);
        vector<int64> ndp(newCap + 1, NEG_INF);
        for (int a = 0; a <= currentCap; ++a) {
            if (dp[a] <= NEG_INF/2) continue;
            for (int b = 0; b <= childCap; ++b) {
                if (a + b > K) break;
                ndp[a + b] = max(ndp[a + b], dp[a] + bestChild[b]);
            }
        }
        dp.swap(ndp);
        currentCap = newCap;
    }
    // Optionally select node u itself (except root 1): increases count by 1 with no local cost
    if (u != 1) {
        int newCap = min(K, currentCap + 1);
        vector<int64> ndp(newCap + 1, NEG_INF);
        for (int t = 0; t <= currentCap; ++t) {
            // do not select u
            ndp[t] = max(ndp[t], dp[t]);
            // select u
            if (t + 1 <= K) ndp[t + 1] = max(ndp[t + 1], dp[t]);
        }
        dp.swap(ndp);
        currentCap = newCap;
    }
    return dp;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T; 
    if (!(cin >> T)) return 0;
    for (int tc = 1; tc <= T; ++tc) {
        cin >> N >> K;
        adj.assign(N + 1, {});
        for (int i = 2; i <= N; ++i) {
            int p, c; 
            cin >> p >> c;
            adj[p].push_back({i, c});
            adj[i].push_back({p, c});
        }
        vector<int64> rootDP = dfs(1, 0);
        int64 best = rootDP[K];              // sum over edges of w * min(s, K+1 - s)
        int64 answer = 2 * best;             // total travel time (round trips across edges)
        cout << "Case " << tc << ": " << answer << '\n';
    }
    return 0;
}
  |