D - Many Repunit Sum Editorial by en_translator
Original proposer: toam
The approach of constructing \(N\) integers consisting of \(A_i\) copies of ones and finding their sum involves two issues.
One is the computational complexity: naively constructing \(N\) integers costs \(O(N^2)\) time.
The other is arbitrary-precision integers: some languages require manual implementation of arbitrary-precision integers.
We will think of solutions to both issues.
Let \(C_k\) be the number of times \(10^k\) contributes to the sum \(\sum_{i=1}^{N}{B_i}\). Since \(B_i=\sum_{j=0}^{A_i-1}{10^j}\), \(C_k\) is the number of indices \(i\) with \(k \lt A_i\); in other words, \(A_i\) contributes by one to \(C_0,C_1,\dots,C_{A_i-1}\).
By using cumulative sums, \(C_0,C_1,\dots,C_{N-1}\) can be found in \(O(N)\) time.
Also, \(C_N,C_{N+1},\dots\) are \(0\).
Perform the following operation for \(i=0,1,2,\dots\):
Add \(\frac{C_i}{10}\) to \(C_{i+1}\), and replace \(C_i\) with the remainder it is divided by \(10\). If \(N \leq i\) and \(C_i=0\), terminate the iteration.
By this process, the values \(C_0,C_1,C_2,\dots\) all become integers less than \(10\), and \(C_i\) is the \((i+1)\)-th least significant digit of the sough answer.
The idea of column additions may help understanding the mechanism.
This can be implemented with a data structure like a stack.
The computational complexity is \(O(N)\).
posted:
last update: