Catch That Cow (bfs(广搜))
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
- Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
- Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
using namespace std;
int m,n,a[100005];
void bfs()
{
int t;
queue<int>st;//定义一个队列
st.push(m);//存入第一个数,人的位置
while(!st.empty())
{
m=st.front();//取出队首的元素
st.pop();//舍去
if(m==n)//结束条件
return;
t=m-1;
if(t>=0&&t<=100000&&!a[t])//!a[t]的作用:判断这个数是否已经存入过队列了;
{
st.push(t);
a[t]=a[m]+1;//标记好是第几次执行的,在前一次执行的次数上加一
}
t=m+1;
if(t>=0&&t<=100000&&!a[t])
{
st.push(t);
a[t]=a[m]+1;
}
t=m*2;
if(t>=0&&t<=100000&&!a[t])
{
st.push(t);
a[t]=a[m]+1;
}
}
}
int main()
{
while(~scanf("%d %d",&m,&n))
{
memset(a,0,sizeof(a));//初始化,注意其包含在头文件<string.h>或<cstring>中
bfs();
cout<<a[n]<<endl;
}
}