Two Buttons
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?
题目大意
对于当前数字,每次操作可以让使其翻倍或减一,求将n变成m的最少操作次数。
题目解读
考虑反向搜索,每次操作使m折半(仅当m为偶数时可行)或加一,可以节省一些常数时间。
算法
直接BFS即可,设dis[i]为i到m的最少操作次数,可得转移方程:
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)))