Problem
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number n.
Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result?
dis[i + 1] = dis[i] + 1
dis[i / 2] = dis[i] + 1 (i ≡ 0 (mod 2))
答案:
dis[n]
时间复杂度:
O(max{m, n})
空间复杂度:
O(max{m, n})
1 import queue 2 3 def bfs(m, n): 4 if (m <= n): 5 return n - m 6 dis = {m : 0} 7 team = queue.Queue() 8 team.put(m) 9 while (not (n in dis)): 10 m = team.get() 11 dis[m + 1] = dis[m] + 1 12 team.put(m + 1) 13 if ((m % 2) or (m // 2 in dis)): 14 continue 15 dis[m // 2] = dis[m] + 1 16 team.put(m // 2) 17 return dis[n] 18 19 n, m = input().split() 20 print(bfs(int(m), int(n)))