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?
5 17
4
代码如下:
#include <iostream>
#include <stack>
#include <math.h>
#include <string>
#include <queue>
#include <cstdio>
using namespace std;
queue<int>map;
int vis[100005];//记录位置
int ans[100005];//记录时间
int n,k;//n是起点 k是终点
int bfs(int pos,int end)
{
map.push(pos);//把农夫的位置放进队列中
ans[pos]=0;//记录开始时间点为0
while(!map.empty())
{
int t=map.front();//当队列里还有数的时候 取t为队列首的数 然后把它拿出来
map.pop();
for(int i=0;i<3;i++)//循环遍历三种情况
{
int x;//x是下一步可以到达的值
if(i==0)
x=t-1;
else if(i==1)
x=t+1;
else if(i==2)
x=2*t;
if(x>2*end||x<0||x>100001)//判断是否越界
continue;
if(!vis[x])//如果x那一格没有被访问过
{
vis[x]=1;//将vis那一格标记为1表示已经走过一次
map.push(x);//把x放进队列
ans[x]=ans[t]+1;//到x的时间等于到t的时间加上1
}
if(x==end)
return ans[k];
}
}
//return pos;
}
int main()
{
scanf("%d %d",&n,&k);
memset(vis,0,sizeof(vis));
memset(ans, 0, sizeof(ans));
while(!map.empty())
map.pop();
if(n>=k)
printf("%d\n",n-k);//如果农夫在牛前面 只要每次往后走一步 走n-k次就行了
else
printf("%d\n",bfs(n,k));//否则就进入BFS广搜
return 0;
}