Problem
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
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 100010;
int n, k;
struct node {//记录当前位置和步数
int x, step;
};
queue<node> Q;
int vis[MAXN];
void bfs() {
int x1, s1;
while(!Q.empty()) {
node temp = Q.front();
Q.pop();
x1 = temp.x;
s1 = temp.step;
if(x1 == k) {
printf("%d\n", s1);
return;
}
if(x1 >= 1 && !vis[x1 - 1]) {//x-1的位置
node t;
vis[x1 - 1] = 1;
t.x = x1 - 1;
t.step = s1 + 1;
Q.push(t);
}
if(x1 <= k && !vis[x1 + 1]) {
node t;
vis[x1 + 1] = 1;
t.x = x1 + 1;
t.step = s1 + 1;
Q.push(t);
}
if(x1 <= k && !vis[x1*2]) {
node t;
vis[x1*2] = 1;
t.x = x1*2;
t.step = s1 + 1;
Q.push(t);
}
}
}
int main() {
while(scanf("%d %d", &n, &k) != EOF) {
while(!Q.empty()) Q.pop();
memset(vis, 0, sizeof(vis));
vis[n] = 1;
node start;
start.x = n, start.step = 0;
Q.push(start);
bfs();
}
return 0;
}