Official

A - Trailing Zeros Editorial by evima


Let us try to decide the values in the order \(A_1, A_2, \dots,A_N\). Then, it is optimal to let \(A_i\) the minimum \(x\) such that \(A_{i-1} \lt x\) and \(\mathrm{ctz}(x) = T_i\), where we assume \(A_0 = 0\) for convenience.
Here, if we rephrase the condition “\(\mathrm{ctz}(x) = T_i\)” using division, it becomes: “\(x\) is an integer divisible by \(2^{T_i}\) but not by \(2^{T_i+1}\).”
Let \(y_1\) and \(y_2\) be the smallest and second smallest integer greater than \(A_{i-1}\) and divisible by \(2^{T_i}\). We can represent \(y_i\) as follows, using the floor function:

\[y_1 = \left(\left\lfloor \frac{A_{i-1}}{2^{T_i}} \right\rfloor + 1 \right) \times 2^{T_i}\]

Also, we have \(y_2 = y_1 + 2^{T_i}\).
Here, exactly one of \(y_1\) and \(y_2\) is not divisible by \(2^{T_i+1}\), so we can choose it for \(A_i\).
Additionally, since \(A_i - A_{i-1} \leq y_2 - A_{i-1} \leq 2^{T_i + 1}\), we can give an upper bound for \(A_N\) as follows, using the constraints:

\[ A_N = \sum_{1 \leq i \leq N} (A_i - A_{i-1}) \leq \sum_{1 \leq i \leq N} 2^{T_i + 1} \leq 2^{41} \times 10^5 \lt 2.2 \times 10^{17} \]

Thus, \(A_N\) is confirmed to be representable by a \(64\)-bit integer, so we can solve the problem by naive computations using types such as long long in C++, in \(\mathrm{O}(N)\) time.

Sample Implementation (C++)

posted:
last update: