I'm resolving a problem from CodeForces: C. Beautiful XOR. This is what the code is supposed to do:
You have two numbers a and b.
You must transform a into b using XOR operations (
a = a ⊕ x) by choosing values for x that lie between 0 and the current value of a.You must find a valid sequence of 100 operations at most or declare it impossible.
This is my code implementing a BFS algorithm to look for numbers by importing collections and checking with something similar to two pointers.
from collections import deque def transformar_xor(a, b): #is they the same no worues no need to operation if a == b: return [] cola = deque([(a, [])]) #this is the tail of the BFS basically visitados = {a} #this is the visits numbers to avoid same number many times max_operacion = 100 #codeforce only acept 100 operations while cola: valor_actual, camino = cola.popleft() if len(camino) >= max_operacion: continue for x in range(1, valor_actual): siguiente_valor = valor_actual ^ x if siguiente_valor == b: return camino + [x] if siguiente_valor not in visitados: visitados.add(siguiente_valor) cola.append((siguiente_valor, camino + [x])) return None #this last code is just because is the way codeforce read the logic t = int(input()) for _ in range(t): a, b = map(int, input().split()) secuencia = transformar_xor(a, b) if secuencia is None: print(-1) else: print(len(secuencia)) if len(secuencia) > 0: print(*secuencia) I think my BFS is checking for too much values in x but I'm not sure what change in this variable. I quit the + 1 but still having the same TLE issue.
for x in range(1, valor_actual + 1): If someone could explain more and help me see where the infinite cycle is coming to produce TLE in my algorithm, I would be appreciative; I've been coding this for almost 2 hours and nothing comes to mind.