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?
5 17
4
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
int N, K, dx;
int step = 0;
struct node {
int N;
int step;
}pre, nex;
int p[200005];
void bfs() {
queue<node> q;
pre.N = N;
pre.step = 0;
p[N] = 1;
q.push(pre);
while(!q.empty()) {
nex = q.front();
q.pop();
if(nex.N == K) {
step = nex.step;
return ;
}
dx = nex.N-1;
if(p[dx] == 0 && dx >= 0 && dx <= 100505) {
pre.N = dx;
pre.step = nex.step+1;
q.push(pre);
p[pre.N] = 1;
}
dx = nex.N+1;
if(p[dx] == 0 && dx >= 0 && dx <= 100505) {
pre.N = dx;
pre.step = nex.step+1;
q.push(pre);
p[pre.N] = 1;
}
dx = nex.N*2;
if(p[dx] == 0 && dx >= 0 && dx <= 100505) {
pre.N = dx;
pre.step = nex.step+1;
q.push(pre);
p[pre.N] = 1;
}
}
return ;
}
int main() {
while(~scanf("%d%d",&N,&K)) {
memset(p, 0, sizeof(p));
step = 0;
bfs();
printf("%d\n",step);
}
return 0;
}