CF Two Buttons (BFS)

时间:2022-05-14 06:03:07
Two Buttons
time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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.

Sample test(s)
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.

刚开始T了,后来加入了剪枝,如果当前这个时间量搜过了那么就不再搜。

 #include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cctype>
#include <queue>
using namespace std; const int MAX = ;
bool VIS[MAX + ];
struct Node
{
int n;
int time;
}; void bfs(int,int);
int main(void)
{
int n,m; while(scanf("%d%d",&n,&m) != EOF)
{
if(n == m)
puts("");
else if(n > m)
printf("%d\n",n - m);
else
bfs(n,m);
}
} void bfs(int n,int m)
{
fill(VIS,VIS + MAX,false);
queue<Node> que;
Node first;
first.time = ;
first.n = n;
que.push(first); while(!que.empty())
{
Node cur = que.front();
que.pop();
for(int i = ;i < ;i ++)
{
Node next = cur;
if(!i)
{
next.n *= ;
next.time ++;
if(next.n > MAX)
continue;
}
else
{
next.n --;
next.time ++;
if(next.n <= )
continue;
}
if(next.n == m)
{
printf("%d\n",next.time);
return ;
} if(VIS[next.n])
continue;
VIS[next.n] = true; que.push(next);
}
} return ;
}