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.
题意:
有两种操作,x*2和x-1,给出n和m,求最少的操作次数,使n变成m
题解:
简单BFS,刚开始剪枝不够,T掉了,要记忆化搜索
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn=10000+100;
struct node
{
int v;
int cur;
};
bool vis[maxn];
queue<node> q;
int main()
{
int n,m;
scanf("%d%d",&n,&m);
node p;
p.v=n;
p.cur=0;
q.push(p);
vis[n]=true;
int ans;
while(!q.empty())
{
node x,now;
x=q.front();
q.pop();
now.cur=x.cur+1;
if(x.v>m)
{
now.v=x.v-1;
if(now.v==m)
{
ans=now.cur;
break;
}
if(!vis[now.v])
{
q.push(now);
vis[now.v]=true;
}
}
else if(x.v<m&&x.v>0)
{
now.v=x.v-1;
if(now.v==m)
{
ans=now.cur;
break;
}
if(!vis[now.v])
{
q.push(now);
vis[now.v]=true;
}
now.v=x.v*2;
if(now.v==m)
{
ans=now.cur;
break;
}
if(!vis[now.v])
{
q.push(now);
vis[now.v]=true;
}
}
}
printf("%d\n",ans);
return 0;
}