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?
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 17Sample Output
4Hint
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.
题意 : 农民有3种走路方式 , 问怎么走可以最短到达目标位置。
思路 : BFS 走感觉还是很好想到的 , 之前一直有一个地方不是很理解 ,就是搜素图的时候什么要标记走过的点什么时候不标记走过的点,现在差不多懂点了 ,每走一步,就把当前这步所有可以到达的位置全部找到,之前走过的点不计入。还有在求步数的搜索题中,特意建一个数组,当前位置的步数等于上一次所走的步数 +1 。
代码 :
/*
* Author: ry
* Created Time: 2017/10/26 9:33:23
* File Name: 2.cpp
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <time.h>
using namespace std;
const int eps = 1e5+5;
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
#define Max(a,b) a>b?a:b
#define Min(a,b) a>b?b:a
#define ll long long
int n, k;
int bu[eps];
void bfs(){
queue<int>que;
que.push(n);
//memset(vis, 0, sizeof(vis));
memset(bu, -1, sizeof(bu));
bu[n] = 0;
while (!que.empty()){
int a = que.front();
que.pop();
if (a == k) break;
for(int i = 0; i < 3; i++){
if (i == 0) {
int b = a - 1;
if (b >= 0 && b < eps && bu[b] == -1){
que.push(b);
bu[b] = bu[a] + 1;
}
}
else if (i == 1){
int b = a + 1;
if (b >= 0 && b < eps && bu[b] == -1){
que.push(b);
bu[b] = bu[a] + 1;
}
}
else {
int b = 2*a;
if (b >= 0 && b < eps && bu[b] == -1){
que.push(b);
bu[b] = bu[a] + 1;
}
}
}
}
}
int main (){
while (~scanf("%d%d", &n, &k)){
bfs();
//for(int i = 1; i <= k; i++){
//printf("%d\t", bu[i]);
//}
//printf("\n");
printf("%d\n", bu[k]);
}
}