Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Assume each node has: vector<Node*> children and an integer cost (or weight) for removal.
- int dp(Node* u) {
- // Base case: if u is a leaf, return its removal cost.
- if(u->children.empty()) {
- return u->cost;
- }
- // Otherwise, compute the cost if we do not remove u:
- int sumChildren = 0;
- for(Node* v : u->children) {
- sumChildren += dp(v);
- }
- // The cost for u is the minimum of:
- // 1. Removing u directly (which cuts off its whole subtree)
- // 2. Not removing u and instead cutting at the children.
- return min(u->cost, sumChildren);
- }
- // To get the answer, since the root cannot be cut:
- int answer(Node* root) {
- int total = 0;
- for(Node* child : root->children) {
- total += dp(child);
- }
- return total;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement