##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
4 1 5 4 3 -5 4 1 1 2 2 3 2 4 5 2 7 -3 1 -4 1 2 2 3 3 4 4 5 6 10 -8 5 -2 7 -6 1 3 3 2 3 4 4 5 4 6
5 -2 -5 -1
You are given a tree with vertices labeled . Each vertex has a (possibly negative) cost .
The tree is rooted at vertex .
Your goal is to delete all vertices using the following operation with minimum total cost.
In one operation, choose a vertex . Let be the set of vertices in the subtree of . If the labels in form a set of consecutive integers, you may delete all vertices in and pay cost .
Find the minimum possible total cost.
Choose vertex .
Its subtree is , so we delete it and pay .
Choose vertex first.
Its subtree is , so we delete and pay .
Now only remains, choose and pay .
Choose vertex first.
Its subtree is , so we delete and pay .
Now the subtree of is , so choose , delete , and pay .
Now the subtree of is , so choose , delete , and pay .
Choose vertex first.
Its subtree is , so we delete and pay .
Choose vertex . Its subtree is , so we delete and pay .
Now the subtree of is , so choose , delete , and pay .
Then choose (subtree ) and pay .
Finally choose (subtree ) and pay .