Advertisement
aqibm

Untitled

Mar 1st, 2025
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. // Assume each node has: vector<Node*> children and an integer cost (or weight) for removal.
  2. int dp(Node* u) {
  3. // Base case: if u is a leaf, return its removal cost.
  4. if(u->children.empty()) {
  5. return u->cost;
  6. }
  7. // Otherwise, compute the cost if we do not remove u:
  8. int sumChildren = 0;
  9. for(Node* v : u->children) {
  10. sumChildren += dp(v);
  11. }
  12. // The cost for u is the minimum of:
  13. // 1. Removing u directly (which cuts off its whole subtree)
  14. // 2. Not removing u and instead cutting at the children.
  15. return min(u->cost, sumChildren);
  16. }
  17.  
  18. // To get the answer, since the root cannot be cut:
  19. int answer(Node* root) {
  20. int total = 0;
  21. for(Node* child : root->children) {
  22. total += dp(child);
  23. }
  24. return total;
  25. }
  26.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement