Link:http://codeforces.com/problemset/problem/520/B
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.
AC code:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<cstdio>
#define LL long long
#define MAXN 100010
using namespace std;
int vis[10010],n;
struct node{
LL x;
LL sp;
}st,ed;
LL bfs()
{
memset(vis,0,sizeof(vis));
queue<node>Q;
node now,next;
int i;
st.sp=0;
Q.push(st);
vis[st.x]=1;
while(!Q.empty())
{
now=Q.front();
if(now.x==ed.x)
return now.sp;
Q.pop();
for(i=1;i<=2;i++)
{
switch(i)
{
case 1:
{
next.x=now.x*2;
if(next.x>0&&next.x<10001&&!vis[next.x])
{
next.sp=now.sp+1;
if(next.x==ed.x)
return next.sp;
Q.push(next);
vis[next.x]=1;
}
break;
}
case 2:
{
next.x=now.x-1;
if(next.x>0&&next.x<10001&&!vis[next.x])
{
next.sp=now.sp+1;
if(next.x==ed.x)
return next.sp;
Q.push(next);
vis[next.x]=1;
}
break;}
}
}
}
return -1;
}
int main()
{
LL n,m;
while(cin>>n>>m)
{
st.x=n;
ed.x=m;
cout<<bfs()<<endl;
}
return 0;
}

本博客探讨了一个关于设备按钮操作的问题,目标是在给定初始数字n和目标数字m的情况下,通过红蓝按钮的操作,求得到达目标数字所需的最小操作次数。详细介绍了输入输出格式、样例解析及AC代码。
1738

被折叠的 条评论
为什么被折叠?



