D: Doubleplusgood
https://open.kattis.com/problems/doubleplusgood
Since there are at most 18 digits in the input, there can be at most 8 plus signs, so the problem is brute-forceable in at most evaluations of the input expression.
To brute force search over all binary strings of length , we increment a counter from to ; the th digit in the binary string is then if and otherwise, where is the bitwise AND function. For a given binary string, we then evaluate the input by using the binary string to decide which symbols to interpret as . Since has higher precedence than , we iterate from left to right, keeping track of the sum of previous concatenated terms and the current number; if the next operation is , we concatenate the next number to the current number, and if the next operation is , then we add the current number to the running sum and reset the current number to . We use a set to keep track of the distinct values that we obtain trying all binary strings. In code:
ints = input().split('+')
lens = list(map(len, ints))
ints = list(map(int, ints))
n = len(ints) - 1
possibilities = set()
for i in range(1 << n):
curr_num = ints[0]
curr_sum = 0
for j in range(n):
if (1 << j) & i:
curr_num = curr_num * pow(10, lens[j+1]) + ints[j+1]
else:
curr_sum += curr_num
curr_num = ints[j+1]
curr_sum += curr_num
possibilities.add(curr_sum)
print(len(possibilities))
Last updated