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.
这个题目是一个宽度优先搜索,使用队列来进行宽度优先搜索把搜索到的元素储存到队列中按照一层一层的顺序来进行搜索,因为每一次都是计算走n步可以走到哪些地方,所以最先走到目的地的就是最短的走法,用一个isvisit数组来记录i这个地方是否搜索过,因为是一层一层的搜索,所以先搜索到i的步数肯定最少,所以可以不用把i加入到队列中继续搜索,这样就节约了时间,在最后进行找到最短路径的时候队列里面可能还有元素,所以在输出答案之后还要将队列清空,代码如下:
#define MAX_C 100005
#include <iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
queue<int> where;
int times[MAX_C];
int isvisit[MAX_C];
int counts;
int flag;
int c;
int person,cow;
int dfs( int po,int co )
{
if ( po == co ) return 0;
where.push(po);
while ( !where.empty())
{
int number = where.front();
where.pop();/**把把首元素取出来之后要将其取出来,防止陷入死循环*/
if ( number - 1 >= 0 && !isvisit [number - 1])/**搜索在这个点下一步可能会出现的状态*/
{
where.push( number - 1);
isvisit[number - 1] = 1;
times[number - 1] = times[number]+1;
}
if ( number - 1 == co ) break;
if ( number + 1<MAX_C && !isvisit[number+1])
{
where.push( number + 1);
isvisit[number+1] = 1;
times[number+1] = times[number]+1;
}
if ( number + 1 == co ) break;
if ( number*2 < MAX_C&&!isvisit[number*2])
{
where.push(number * 2);
isvisit[number*2] = 1;
times[number*2] = times[number]+1;
}
if ( number * 2 == co ) break;
}
return times[co];
}
int main()
{
while ( cin >> person >> cow )
{
memset(isvisit,0,sizeof(isvisit));
memset(times,0,sizeof(times));
cout << dfs(person,cow) << endl;
while(where.size())
where.pop();
}
}