Official Analysis (C++, Python)
Explanation
One can observe that the answer for is for (in other words, a geometric sequence starting at three with common ratio two). Note that this doesn't apply to , because the answer for is .
To see why this is true, consider the function which denotes the decimal number whose digits are the binary representation of . Particularly, . If , the first call subtracts one in decimal, and the next call converts the resulting digits by parity if is even. Thus, for , if is odd then one call sends to , and otherwise if is even then two calls send to .
An example to illustrate the odd case is . Only one operation is needed for odd because by definition, the binary representation of odd ends in one, which turns to zero. On the other hand, , so even needs a second call.
Thus, = .
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, .
Our algorithm is as follows: convert to binary with one operation if it isn't already. Then, loop through the digits and add up the contributions for the ones. If the th (zero-indexed) digit is one, the power of ten this corresponds to is . To handle overflow, apply the modulo at each intermediate step and precompute powers of two modulo.
Implementation
Time Complexity:
MOD = 10**9 + 7for _ in range(int(input())):x = list(input())n = len(x)answer = 0# make digits binary if not alreadyif not all(c in "01" for c in x):answer = 1for 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!