Problem Statement:
Let A and B be two N bit numbers (MSB to the left). You are given initial values for A and B, and you have to write a program which processes three kinds of queries:
set_a idx x:
SetA[idx]
tox
, where \$0 \le idx < N\$, whereA[idx]
is idx'th least significant bit of A.
set_b idx x:
SetB[idx]
tox
, where \$0 \le idx < N\$, whereB[idx]
is idx'th least significant bit of B.
get_c idx:
PrintC[idx]
, where \$C=A+B\$, and \$0\le idx\$Input Format:
First line of input contains two integers \$N\$ and \$Q\$ consecutively (\$1 \le N \le 100000\$, \$1\le Q \le 500000\$). Second line is an \$N\$-bit binary number which denotes initial value of \$A\$, and the third line is an \$N\$-bit binary number denoting initial value of \$B\$. \$Q\$ lines follow, each containing a query as described above.Output Format:
For each query of the typeget_c
, output a single digit \$0\$ or \$1\$. Output must be placed in a single line.Sample Input:
5 5 00000 11111 set_a 0 1 get_c 5 get_c 1 set_b 2 0 get_c 5
Sample Output:
100
I solved this question and I tried to optimize by reducing the number of calculations for bit addition, but am still getting time-limit-exceeded where the time exceeds 10 seconds for Python.
n, q = map(int, raw_input().split())
A_inp = list(raw_input())
B_inp = list(raw_input())
Query_output = []
def LSB(idx, n):
return (n - 1) - (int(idx))
def Bit_Add(a, b, n):
length = len(a)
output = []
carry = 0
for i in range(length):
if a[i] == "1" and b[i] == "1":
if carry == 1:
output.append(1)
carry = 0
else:
output.append(0)
carry = 1
elif a[i] == "1" or b[i] == "1":
if carry == 1:
output.append(1)
carry = 0
else:
output.append(0)
else:
if carry == 1:
output.append(1)
carry = 0
if carry == 1:
output.append(1)
return output[::-1]
f = 0
for i in range(q):
query = raw_input().split()
if query[0][0:3] == "set":
Value = query[0][4]
idx = LSB(int(query[1]), n)
if Value == "a":
A_inp[idx] = query[2]
elif Value == "b":
B_inp[idx] = query[2]
f = 0
else:
if f == 1:
idx = LSB(query[1], len(output))
Query_output.append(output[idx])
else:
output = Bit_Add(A_inp, B_inp, n)
idx = LSB(query[1], len(output))
Query_output.append(output[idx])
f = 1
print int(''.join(["%d"%x for x in Query_output]))