用最少的操作將數字m轉換爲n。允許的操作是減1和乘以2.用於算術運算的BFS
例如:4和6.答案是2. 第一次操作:-1 - > 4-1 = 3 第二次操作:* - > 3 * 2 = 6。
我對特定輸入(src = 26,dst = 5)使用BFS方法需要很長時間。難道我做錯了什麼?
from queue_class import queue
class node:
def __init__(self, value, level, parent):
self.level = level
self.value = value
self.parent = parent
def get_minimum_distance(src, target, q):
if src == target:
return 0
seen_list = []
data = node(src, 0, -1)
q.enqueue(data)
while not q.isempty():
data = q.dequeue()
if data == "sentinel":
break
if data.value == target:
# let's print what has got me here
while data.parent != -1:
print(data.value)
data = data.parent
return "finally reached"
if data.value in seen_list:
continue
seen_list.append(data.value)
# two operations are allowed i.e. -1 and multiplication by 2
# check if two numbers have opposite sign and if they have
# then check if the current number being subtracted from is a negative
# number. If it is, then there is no point subtracting 1 from that
if ((data.value^target) < 0 and data.value > 0) or (data.value^target >= 0):
q.enqueue(node(data.value - 1, data.level + 1, data))
q.enqueue(node(data.value * 2, data.level + 1, data))
return -1
q = queue(1 << 20)
print(get_minimum_distance(26, 5, q))
隊列實現完成here。
感謝保羅: 下面是我在python下面的代碼想出來的代碼,它完美的工作。
def get_minimum_operations(src, dst):
step = 0
operations = []
if src == dst:
return 0
if dst < src:
return src-dst
while dst > src:
if dst & 0x01:
step += 1
operations.append("-1")
dst = (dst+1) >> 1
operations.append("*2")
step += 1
for i in range(0, src-dst):
operations.append("-1")
return (((src - dst) + step), operations)
src = 38
dst = 100
output = ""
(steps, operations) = get_minimum_operations(src, dst)
print(steps)
try:
while operations:
i = operations.pop()
if i == "*2":
if output == "":
output += "(" + str(src) + "*2" + ")"
else:
output = "(" + output + "*2" + ")"
if i == "-1":
if output == "":
output += "(" + str(src) + "-1" + ")"
else:
output = "(" + output + "-1" + ")"
except IndexError:
pass
print(output)
對不起,但你的回答不明確。能否請您詳細說明「由於以下事實,可輕易將收縮最小化:(a - 1)* 2 = a * 2 - 2」?這將是很好的舉一些例子,你的解決方案不起作用http://ideone.com/OQNsY2 –
@nomanpouigt關於最小化替換次數的東西只依賴於你可以寫'(a - 1) * 2'而不是'a * 2 - 1 - 1',從而將操作次數減少一次。同樣適用於更高的數字。至於你的代碼,第8行有一個錯誤('int s = a <<(n-b);'應該是'int s =(a << n) - b;')。 Sry,我忘了把這些括號放進代碼中,我會糾正它的。只需更換該線路,它就可以工作。 – Paul
可以理解,但這個事實如何幫助減少從a轉換爲b時的操作次數?它只有在我們想從a變換到b時纔有用,它應該等於(a-1)* 2(這不是2的冪,而只是偶數)。但是在b不等於( a-1)* 2然後呢? –