Official

F - GCD or MIN Editorial by en_translator


First, the final value can be represented as the GCD of one or more of \(A_1, A_2, A_3, \dots, A_N\). (Because if \(x\) and \(y\) can both be represented this way, so can both \(\min(x, y)\) and \(\gcd(x, y)\).)

Also, since \(\min(x, y)\) and \(\gcd(x, y)\) are both less than or equal to \(\min(x, y)\), we can see that the final value is less than or equal to \(\min{\{A\}}\).

Now, if a number satisfies those two conditions, is it always a possible final value?
It is. We will show the specific procedure.

Assume that a final value \(r\) is the GCD of \(A_{x_1}, A_{x_2}, A_{x_3}, \dots, A_{x_k}\). First, combine \(A_{x_1}, A_{x_2}, A_{x_3}, \dots, A_{x_k}\) with \(\gcd\).
Now we have \(r\) and some elements of \(A\) on the blackboard. Since \(r \le \min{\{A\}}\), we can combine all the remaining numbers \(\min\) so that we have \(r\) as the final value.

Based on these fact, let us adopt the strategy where iterating all the numbers that “can be represented as the GCD of one or more of \(A_1, A_2, A_3, \dots, A_N\)” explicitly, then count the number of numbers that are less than or equal to \(\min{\{A\}}\).
A number \(x\) “can be represented as the GCD of one or more of \(A_1, A_2, A_3, \dots, A_N\)” if and only if “there are one or more elements of \(A\) that are multiples of \(A\), and their GCD is equal to \(x\)”.
Therefore, they can be found by the following procedure.

  • First, prepare an associative array \(t\) (which is initially empty)
  • For all \(A_i\), do the following:
    • For each of \(A_i\)’s divisor \(j\), let \(t_j \leftarrow \gcd(t_j, A_i)\). If \(t_j\) does not exist, let \(t_j \leftarrow A_i\).
  • Those \(j\) such that \(t_j = j\) are the numbers that “can be represented as the GCD of one or more of \(A_1, A_2, A_3, \dots, A_N\)

Now let us consider the complexity.
We can enumerate the divisors in a total of \(O(N \sqrt{\max{\{A\}}})\) time.
Let \(d(n)\) be the maximum number of divisors of an integer less than or equal to \(n\). If we use certain associative arrays like hashmaps, where each operation is done in an \(O(1)\) time, then operations of the associative array are done in a total of \(O(N d(\max{\{A\}}))\), and the calculations of \(\gcd\) are done in a total of \(O(N d(\max{\{A\}}) \log(\max{\{A\}}))\) time.

Since \(d(10^9) = 1344\), this solution fits in the time limit.

posted:
last update: