Editorial
For fixed distinct vertices and , consider Alice's score minus Bob's score. A piece ending at contributes , a piece ending at contributes , and every other piece contributes .
Let be the final contribution of one piece currently on vertex . Suppose it is moved to a neighbor on turn .
- If , turn has already passed. The contribution is if , if , and otherwise.
For odd , Alice chooses the maximum available value. For even , Bob chooses the minimum. Thus these values can be computed from down to .
This argument does not assume that pieces on one vertex can be moved separately. If pieces have gathered on vertex , the part of the score difference affected by the chosen neighbor is multiplied by . We always have , and the contributions of pieces on other unprocessed vertices are unaffected. Therefore, the maximizing or minimizing neighbor is independent of , and the contribution can be applied linearly to every piece.
Running this DP separately for all pairs would be too slow. We use the fact that every contribution is one of .
Let indicate whether . Choosing neighbor produces if when , or if is true when . Therefore:
- for odd , is true if at least one neighbor satisfies the condition;
- for even , is true if every neighbor satisfies the condition.
This recurrence does not contain . Hence the number of pieces contributing ,
depends only on .
Similarly, let indicate whether . At an odd vertex every neighbor must produce , while at an even vertex one such neighbor is enough. This recurrence does not contain , so
depends only on .
The score difference after optimal play for pair is exactly . Compute and by scanning the vertices in decreasing order for every target vertex.
Finally, sort all values . For each , use binary search to count values satisfying , and subtract one if the counted choices include .
The total time complexity is . Since a connected graph has , this can also be written as . The space complexity is .
Solution written by GPT6