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?
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 17Sample Output
4Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
在本题中,农场主有三种方式,一种是往前走一步,一种是往后走一步,还有一种是瞬移到原来位置的两倍。
在BFS循环的时候就可以将这三种
扫描二维码关注公众号,回复:
2718696 查看本文章
操作进行处理。 走过的位置标记。代表不会走回原来的位置。因为不标记的话,会导致死循环.
在找到牛的时候跳出。
代码:
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 100000+5;
int n,k;
int vis[maxn];
struct point
{
int x,step; //坐标和时间
};
int check(int x)//判断是否满足条件
{
if(x>=0&&x<=100000 && vis[x]==0)
return 1;
return 0;
}
int bfs()
{
memset(vis, 0, sizeof(vis));
queue< point > q;
point st,now;
//将起点加入队列
st.x = n;
st.step = 0;
vis[st.x] = 1; // 记录已经访问
q.push(st);
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x == k) //结束条件
{
return now.step;
}
//循环三种情况
for(int j = 0 ; j < 3; j++)
{
point next = now;//为了复制now的step
if(j == 0)
{
next.x = now.x + 1;
}
else if(j == 1)
{
next.x = now.x - 1;
}
else if(j == 2)
{
next.x = 2 * now.x;
}
if(check(next.x)) //如果这个点满足条件
{
next.step++;
vis[next.x] = 1;
q.push(next);
}
}
}
return -1;
}
int main()
{
scanf("%d%d",&n,&k);
printf("%d\n",bfs());
}