Editorial
If , performing the operation on the only vertex makes its value . Therefore, the answer is .
Now assume .
First, no vertex can have final value at least . For a vertex to become at least , every neighbor of must have value at least right before the operation on . However, if a neighbor of was operated before and became at least , then at that time its neighbor should already have value at least . But had not been operated yet, so its value was still . This is a contradiction. Thus, final values can only be .
For , we can make every vertex at least . For example, perform the operation on every vertex in any order. Since the minimum adjacent value is always at least , each operated vertex becomes at least .
Now consider the vertices whose final value is . No two adjacent vertices can both have value . Suppose adjacent vertices and both become . Let be the one operated earlier. When was operated, had not been operated yet, so its value was . Therefore, could not become , a contradiction.
So the set of vertices with value must be an independent set.
Conversely, for any independent set in the tree, we can make exactly those vertices have value . First, perform the operation on all vertices not in . Their values become at least . Then perform the operation on all vertices in . Since is independent, every neighbor of each vertex in lies outside and already has value at least . Thus, every vertex in becomes .
Therefore, for , the maximum sum is
where is the size of a maximum independent set of the tree.
The maximum independent set of a tree can be computed by dynamic programming. Root the tree at vertex and define:
- : the maximum number of chosen vertices in the subtree of when is not chosen
- : the maximum number of chosen vertices in the subtree of when is chosen
Then:
The maximum independent set size is , and the answer is .
The time complexity is , and the memory usage is .