C - Catch That Cow
农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不动。最少要花多少时间才能抓住牛?
Input
一行: 以空格分隔的两个字母: N 和 K
Output
一行: 农夫抓住牛需要的最少时间,单位分钟
Sample Input
5 17
Sample Output
4
Hint
农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.
解题思路:
本题在需要注意的是不要忘记标记,如果不标记的话就会不知道哪条路走过了,哪条路没走过,这样的话就会弄混;还有就是每一层走过只加一分钟,这一点不要弄错;还有一点需要知道的是要记得用bool看运算结果为真或为假,超出范围内就不进行下去,这样就避免代码循环运行下去。
代码如下:
#include"iostream"
#include"algorithm"
#include"cstring"
#include"queue"
using namespace std;
int n,m;
struct state
{
int x,stp;
};
int vst[100005];
bool cheak(state a)
{
if(a.x < 0 || a.x > m+2 || vst[a.x] == 1)
{
return 0;
}
return 1;
}
void bfs(state a)
{
a.stp=0;
queue<state> q;
state now,next;
vst[a.x]=1;
q.push(a);
while(!q.empty())
{
now=q.front();
q.pop();
// cout<<"x= "<<now.x<<endl;
if(now.x==m)
{
cout<<now.stp<<endl;
return ;
}
next.x=now.x*2;
next.stp=now.stp+1;
if(cheak(next))
{
vst[next.x]=1;
q.push(next);
}
next.x=now.x+1;
next.stp=now.stp+1;
if(cheak(next))
{
vst[next.x]=1;
q.push(next);
}
next.x=now.x-1;
next.stp=now.stp+1;
if(cheak(next))
{
vst[next.x]=1;
q.push(next);
}
}
return ;
}
int main()
{
while(cin >> n>> m)
{
if(n >= m)
{
cout<<n-m<<endl;
continue;
}
state a;
a.x=n;
memset(vst,0,sizeof(vst));
bfs(a);
}
return 0;
}