暴力 + 位运算
因为总共有16个格子, 每个格子都有两种选择(点击或者不点), 因此, 总共2^16=65536种.
对于每种开关选择, 最多有16下点击. 每个点击的影响, 可以预处理得到. 通过异或位运算, 对于每个点击, 在O(1)时间里面得到影响.
因此, 时间复杂度为O(16 * 2^16)
时间复杂度
O(16 * 2^16)
Python 代码
Log2 = {(1 << i) : i for i in range(16)}
def decode(state):
idxs = []
idxs2 = []
while state:
tmp = state & (-state)
state -= tmp
ind = Log2[tmp]
i, j = divmod(ind, 4)
idxs.append((i, j))
idxs2.append(ind)
return idxs, idxs2
f = [0] * 16
for i in range(4):
for j in range(4):
ind = i * 4 + j
val = 0
for r in range(4):
ind2 = r * 4 + j
val += 1 << ind2
for c in range(4):
if c != j:
ind2 = i * 4 + c
val += 1 << ind2
f[ind] = val
def check(idxs):
B = A
for idx in idxs:
B ^= f[idx]
return B == 0
A = 0
for i in range(4):
for j, a in enumerate(input()):
if a == "+":
ind = i * 4 + j
A += 1 << ind
ans = 17
ans_idxs = [[-1] * 2 for _ in range(ans)]
for state in range(1 << 16):
idxs, idxs2 = decode(state)
if len(idxs) >= ans: continue
if check(idxs2):
ans = len(idxs)
ans_idxs = idxs
print(ans)
for i in range(ans):
for j in range(2):
print(ans_idxs[i][j] + 1, end=" ")
print()