Description
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
Hint
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.
题解:农夫追母牛,有走一步退一步或者走两倍的路程三中方法,问最少次数追上母牛(母牛不动),操作进行处理时走过的位置要标记,代表不会走回原来的位置。如果不标记的话,会导致死循环,爆内存。
在找到牛的时候跳出。
在判断是否越界的时候,当牧场主所在的位置大于m的时候,就认为他越界。因为他有可能先去到m+x(任意数)的时候 ,在返回。所以再判断是时候,越界的最大值最好开大一些。
代码如下:
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <queue>
using namespace std;
const int MAX=1e2+10;
typedef long long LL;
int map[100010];
int m,n;
struct node
{
int x,y;//x为当前位置,y为计数器
};
int bfs(int k)
{
queue<node>q;
node o;
o.x=k;
o.y=0;
map[k]=1;//每次标记
q.push(o);
while(!q.empty())
{
o=q.front();//结构体可以直接赋值
q.pop();
if(o.x==m)
return o.y;
for(int i=0; i<3; i++) //三种方案
{
if(i==0)
{
node w;
w.x=o.x+1;
if(w.x>=0&&w.x<100010&&!map[w.x])//判断是否越界和是否走过
{
w.y=o.y+1;//计数
map[w.x]=1;
q.push(w);
}
}
if(i==1)
{
node w;
w.x=o.x-1;
if(w.x>=0&&w.x<100010&&!map[w.x])
{
w.y=o.y+1;
map[w.x]=1;
q.push(w);
}
}
if(i==2)
{
node w;
w.x=o.x*2;
if(w.x>=0&&w.x<100010&&!map[w.x])
{
w.y=o.y+1;
map[w.x]=1;
q.push(w);
}
}
}
}
return 0;
}
int main()
{
cin>>n>>m;
printf("%d\n",bfs(n));
return 0;
}
萌新代码,请多包涵^_^