Two Buttons
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.
思路:
该题可以直接模拟,也可以用广搜来写,类似于最短路。
直接模拟的思路:倒着找,如果是偶数,则直接除2,如果是奇数,则加1除2,
直到找到目标。而广搜可以套模板来写。
模拟代码:
#include<stdio.h>
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
int count=0;
if(n>=m)
{
count=n-m;
}
else
{
while(n!=m)
{
if(m%2!=0||n>m)
{
m++;
count++;
}
else
{
m=m/2;
count++;
}
}
}
printf("%d\n",count);
}
return 0;
}
广搜代码:
#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
const int maxn=1e4+100;
int book[maxn];//该数组用于标记
int m,n;
struct node
{
int x;
int step;
};
int judge(int x)//判断是否走过
{
if(x<1||x>maxn)
return 0;
if(book[x])
return 0;
return 1;
}
void bfs(int x)
{
memset(book,0,sizeof(book));
node now,next;
queue<node>q;
now.x=x;
book[now.x]=1;
now.step=0;
q.push(now);//初始化队列
while(!q.empty())//直到队列为空为止
{
now=q.front();//取出队首元素
q.pop();//删除队首元素
next.step=now.step+1;
next.x=now.x-1;//减1搜索
if(judge(next.x))//调用函数,判断是否能走
{
book[next.x]=1;//标记已经走过
if(next.x==m)//结束条件
{
printf("%d\n",next.step);
return ;
}
q.push(next);//下一个元素入队
}
next.x=now.x*2;//乘2搜索
if(judge(next.x))//结束条件
{
book[next.x]=1;//标记已经走过
if(next.x==m)//结束条件
{
printf("%d\n",next.step);
return ;
}
q.push(next);//下一个元素入队
}
}
return ;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==m)
{
printf("0\n");
continue;
}
bfs(n);
}
return 0;
}