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?
The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .
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.
4 6
2
10 1
9
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.
1 #include<stdio.h> 2 #include<queue> 3 #include<set> 4 using namespace std; 5 int n , m ; 6 7 int main () 8 { 9 //freopen ("a.txt" , "r" , stdin) ; 10 while (~ scanf ("%d%d" , &n , &m)) { 11 queue <pair <int , int> > q ; 12 set <int> s ; 13 q.push ( {n , 0} ) ; 14 while (!q.empty ()) { 15 pair <int , int> p = q.front () ; 16 q.pop () ; 17 if (p.first <= 0 ) 18 continue ; 19 if (p.first == m) { 20 printf ("%d " , p.second) ; 21 break ; 22 } 23 else { 24 s.insert (p.first) ; 25 if (s.count (p.first - 1 ) == 0 ) { 26 q.push ( {p.first - 1 , p.second + 1 } ) ; 27 } 28 if (p.first < m && s.count (p.first * 2) == 0 ) { 29 q.push ( {p.first * 2 , p.second + 1 } ) ; 30 } 31 } 32 } 33 } 34 return 0 ; 35 }
我是用bfs(看别人的),见识了set 和 pair 的用法。
There is, however, an even faster solution. The problem can be reversed as follows: we should get the number n starting from m using the operations "add 1 to the number" and "divide the number by 2 if it is even".