Editorial
Let be the maximum score obtainable by sending balls into the subtree rooted at vertex .
First handle vertices with exactly one child. If the only child of is , every ball must move to , so
Therefore, contracting every vertex with exactly one child does not change any distribution or score. A unary chain starting at the original root can be contracted in the same way. Every vertex in the contracted tree is now either a leaf or has at least two children.
For a leaf , every ball stops there, hence
Now consider a vertex with children. Write , where . Independently of the chosen order, every child receives balls, and exactly the first children receive one additional ball.
For a child , the gain from receiving that additional ball is
Any subset of children can be placed in the first positions. Therefore, the optimal choice is to select the largest values of , giving
For one fixed , all states can be computed together. Sort all values in descending order and use their prefix sums.
Computing every state up to at every vertex is still too slow. Let be the maximum number of balls for which a state at can be required. For the contracted root, . If has children, each child can receive at most
balls. Thus, only are needed.
To bound the number of states, define . For every child ,
Every internal vertex of the contracted tree has , so a positive value of is at least halved on every edge. Moreover, the sum of over all children of one vertex does not exceed the parent's . Hence, the sum of over one depth is at most , and positive values can occur on only depths. Vertices with contribute only a constant number of states each.
Therefore, the total number of DP states is
Sorting the marginal gains for each quotient group gives total time complexity
and the memory complexity is
Scores may be negative, and their absolute values can reach , so 64-bit integers are required.
Solution written by GPT5.6