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?

 

Input

  The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .

 

Output

  Print a single number — the minimum number of times one needs to push the button required to get the number m out of number n.

 

Examples
  input
    4 6
  output
    2
  input
    10 1
  output
    9

Note

  In the first example you need to push the blue button once, and then push the red button once.

  In the second example, doubling the number is unnecessary, so we need to push the blue button nine times.

 

 
 
题目大意
  对于当前数字,每次操作可以让使其翻倍或减一,求将n变成m的最少操作次数。

 

题目解读
  考虑反向搜索,每次操作使m折半(仅当m为偶数时可行)或加一,可以节省一些常数时间。

 

算法
  直接BFS即可,dis[i]im的最少操作次数,可得转移方程:

      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)))
posted @ 2018-06-19 02:00  Efve  阅读(215)  评论(0编辑  收藏  举报