一、内容

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

二、思路

  • 用vis数组记录当前点是否被访问过,被访问就不用再入队了。
  • 每次3种状态 *2 +1 -1
  • 若n大于k的话只能向后移动 输出n-k即可

三、代码

#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 1e5 + 5;
int n, k, step[maxn], vis[maxn];
 
void bfs() {
 	queue<int> q;
 	q.push(n);
 	vis[n] = 1;
 	while (q.size()) {
 		int t = q.front();
		q.pop();
		int next;
		for (int i = 0; i < 3; i++) {
			if (i == 0) next = t * 2;
			else if(i == 1) next = t + 1;
			else next = t - 1;
			if (next <= 0 || next >= maxn) continue;
			if (!vis[next]) {
				q.push(next);
				vis[next] = 1;
				step[next] = step[t] + 1;
			}
			if (next == k) {
				printf("%d", step[k]);
				return;
			}
		}
	}
}

int main() {
	scanf("%d%d", &n, &k);
	if (n >= k ){
		printf("%d", n - k);
	} else {
		bfs();
	}
	
	return 0;
}