E - Choose Two and Eat One Editorial by spheniscine


Note that exponentiating a value modulo \(M\) (i.e. \(x^y \text{ mod } M\)) can be quickly calculated using binary exponentiation in \(O(\log y)\) time, so we can easily calculate the score increase for every operation.

Consider representing Takahashi’s actions as a directed graph, where edge \(u \rarr v\) represents picking balls \(u\) and \(v\) and eating ball \(u\). Then, any valid sequence of actions is a directed acyclic graph with \(N-1\) edges, \(N\) nodes, and each node with an out-degree not more than \(1\); in other words, a parent-directed tree. In fact, we can construct a valid sequence of actions for any \(N\)-node tree, and we don’t really care about the directions; any node in the tree could be arbitrarily picked as the root without changing the final score.

To find the maximum possible score, we can first build a weighted complete graph, where the weight for the edge between \(u\) and \(v\) is the score obtained by doing an operation involving balls \(u\) and \(v\). We want to find a spanning tree in this graph with the maximum total weight, aka the maximum spanning tree. Both minimum and maximum spanning trees can be found using Kruskal’s algorithm. In short, sort the edges from most-preferred to least-preferred, then use disjoint set union (DSU) to try each edge in the sorted order, choosing to use each edge only if the DSU reports a new connection.

This will solve the problem with \(O(N^2)\) space and \(O(N^2 (\log N + \log M))\) time. The constraints are also loose enough to accept \(O(N^3)\) time solutions (which may admit solutions that don’t use the DSU data structure).

posted:
last update: