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
这道题是采用广度优先搜索和用队列来存放数据。
广度优先搜索是分层,起点是0 层,然后第一个分之是1 层一次往下寻找,
先把起点的位置和步数放在队列里,然后再访问第二层······················
//广度优先搜索,用队列来存放。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const int MAXN =100000; // c++中定义一个常数,而在c中则是用#define MAXN 100000;
int visited[MAXN+10]; //设一个数组来记录节点是否被走过,(查重) 为真时表示走过这个点
struct step //建立一个step的一个结构体
{
int x; //农夫的位置
int steps; //所走的步数
step(int xx,int s):x(xx),steps(s) {} //是一个构造函数:是在声明变量时调用的 。。。
//:x(xx),steps(s)简单写法,将成员变量x初始化为参数xx,成员变量steps初始化为参数s;
//也可以写成:step(int xx=0,int s=0){this->x=xx;this->steps=s;}
};
queue<step> q; //建立一个step结构体形式的队列。
int main()
{
int n,k;
cin>>n>>k;
memset(visited,0,sizeof(visited)); //初始化为0,为1时则表示已走过。
q.push(step (n,0)); //将起始位置先放入队列里n,0代表steps所走的步数。
visited[n]=1; //将起始位置记录
while(!q.empty()) //
{
step s=q.front(); //将队列的头打出。放在close里
if(s.x==k) //如果遇到终节点则结束。
{
cout<<s.steps<<endl;
return 0;
}
else
{
if(s.x-1>=0&&!visited[s.x-1]) //向左走一步
{
q.push(step(s.x-1,s.steps+1));
visited[s.x-1]=1;
}
if(s.x+1<=MAXN&&!visited[s.x+1]) //向右走一步。
{
q.push(step(s.x+1,s.steps+1));
visited[s.x+1]=1;
}
if(s.x*2<=MAXN&&!visited[s.x*2]) //走的时原来的两倍位置。
{
q.push(step(s.x*2,s.steps+1));
visited[s.x*2]=1;
}
q.pop(); //弹出
}
}
return 0;
}