Table of Contents

ExplanationImplementation

Official Analysis (C++, Python)

Explanation

One can observe that the answer for 10a10^a is 32a13 \cdot 2^{a - 1} for a>0a > 0 (in other words, a geometric sequence starting at three with common ratio two). Note that this doesn't apply to a=0a = 0, because the answer for x=1x = 1 is 11.

To see why this is true, consider the function B(n)B(n) which denotes the decimal number whose digits are the binary representation of nn. Particularly, 10a=B(2a)10^a = B(2^a). If x=B(n)x = B(n), the first call subtracts one in decimal, and the next call converts the resulting digits by parity if nn is even. Thus, for n1n \ge 1, if nn is odd then one ff call sends B(n)B(n) to B(n1)B(n - 1), and otherwise if nn is even then two ff calls send B(n)B(n) to B(n1)B(n - 1).

An example to illustrate the odd nn case is B(13)=1101,f(1101)=1100=B(12)B(13) = 1101, f(1101) = 1100 = B(12). Only one ff operation is needed for odd nn because by definition, the binary representation of odd nn ends in one, which turns to zero. On the other hand, B(12)=1100,f(1100)=1099,f(1099)=1011=B(11)B(12) = 1100, f(1100) = 1099, f(1099) = 1011 = B(11), so even nn needs a second call.

Thus, ans(10a)\operatorname{ans}(10^a) = n=12a(1 if n odd, 2 if n even)=32a1\sum_{n=1}^{2^{a}}\left(1\ \operatorname{if}\ n\ \operatorname{odd},\ 2\ \operatorname{if}\ n\ \operatorname{even}\right) = 3 \cdot 2^{a - 1}.

Any number in a binary state is just the sum of powers of ten, corresponding to the positions of its one digits. Operations on the lowest power of ten do not affect higher powers of ten while handling it, so the contributions from the different one bits can be computed and added independently. For example, ans(10110)=ans(10000)+ans(100)+ans(10)\operatorname{ans}(10110) = \operatorname{ans}(10000) + \operatorname{ans}(100) + \operatorname{ans}(10).

Our algorithm is as follows: convert xx to binary with one f(x)f(x) operation if it isn't already. Then, loop through the digits and add up the contributions for the ones. If the iith (zero-indexed) digit is one, the power of ten this corresponds to is len(x)i1\operatorname{len}(x) - i - 1. To handle overflow, apply the modulo at each intermediate step and precompute powers of two modulo.

Implementation

Time Complexity: O(N)\mathcal{O}(N)

MOD = 10**9 + 7
for _ in range(int(input())):
x = list(input())
n = len(x)
answer = 0
# make digits binary if not already
if not all(c in "01" for c in x):
answer = 1
for i in range(n):

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!