Official

D - Avoid Coprime Game Editorial by evima


Let \(M=\max(A)\).

In this kind of problem, the first solution that comes to mind could be a bit DP that maintains the integers remaining on the blackboard, but it is way too slow for the case \(N=2 \times 10^5\). How can we avoid enumerating all possible sets of remaining integers on the blackboard?

Here is an important fact: if \(1 < \gcd(A_i,\ G) < G\) for some \(A_i\), then \(A_i\) always remain on the blackboard. Thus, if we only consider such operations that make \(G\) smaller, we may ignore the set of the remaining integers.

Then, a potential issue is a situation where it is optimal for both players to play so that \(G\) does not change. However, in such a situation, they will keep choosing a multiple of \(G\) until there is none, so one can foresee from the parity of the number of multiples of \(G\) which player will be stuck and have to make \(G\) smaller.

The observation above suggests that the winner from a certain situation depends only on the current \(G\) and the current player to play. This can be proved by induction on \(G\).

Thus, we can define and compute the following DP table:

\(dp[g][p]:\) the winning player if the current \(G\) is \(g\) and the current player is \(p\).

Here, we have to check if there is \(A_i\) such that \(\gcd(A_i, \ g)=d\) for each divisor \(d\ (d\neq g)\), and find the parity of the number of multiples of \(g\) among \(A_i\). The latter can be precomputed in \(O(M\log M)\) time.

For the former, let \(f_{g,d}\) be the number of \(A_i\) such that \(\gcd(A_i,\ g)=d\). If \(A_i\) is a multiple of \(d\), then \(\gcd(A_i,\ g)\) is a multiple of \(d\) and a divisor of \(g\), so the sum of \(f_{g,d'}\) over all integers \(d'\) that are multiples of \(d\) and divisors of \(g\) equals the number of divisors of \(d\) among \(A_i\). Thus, we can compute \(f_{g, d}\) in descending order of \(d\). To evaluate the complexity of this method, let us evaluate the number of triples \((a,\ b,\ c)\ (1 \leq a \leq b \leq c \leq M)\) such that \(b\) is a multiple of \(a\) and \(c\) is a multiple of \(b\), which are what we eventually seek. For a fixed \(A\), there are \(O(\frac{M}{A}\log{\frac{M}{A}})\) pairs of \(b\) and \(c\), so there are \(O(M\log^2 M)\) triples.

Therefore, the problem can be solved in \(O(N+M\log^2 M)\) time, which is fast enough.

posted:
last update: