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
Output
Sample Input
5 17
Sample Output
4
Hint
经典BFS。对所有情况进行一次搜索,最先找到的就是解。
代码如下:
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N=1000000;
int map[N+10],n,k;
struct point
{
int x,step;
} ;
int check(int x)
{
if(x<0||x>N||map[x])
{
return 0;
}
return 1;
}
int bfs(int x)
{
queue<point> q; //队列
point now,next;
now.x=x;now.step=0;
map[x]=1; //标记
q.push(now); //将now插入队列
while(!q.empty())
{
now=q.front(); //将先进入队列的元素取出存入now
q.pop(); //取出后删除
if(now.x==k) return now.step;
next=now;
next.x=now.x+1;
//三种情况
if(check(next.x))
{
next.step=now.step+1; //步数加一;
map[next.x]=1;//标记
q.push(next);
}
next.x=now.x-1;
if(check(next.x))
{
next.step=now.step+1;
map[next.x]=1;
q.push(next);
}
next.x=now.x*2;
if(check(next.x))
{
next.step=now.step+1;
map[next.x]=1;
q.push(next);
}
}
return -1;
}
int main()
{
scanf("%d%d",&n,&k);
memset(map,0,sizeof(map));//标记为0(表示未搜索过)
cout<<bfs(n)<<endl;
return 0;
}
博客已搬:
洪学林博客