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
Output
Sample Input
5 17
Sample Output
4
Hint
三种操作BFS,注意边界即可
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
#define N 100005
bool vis[N<<1];
int a[N<<1];
queue<int> q;
int main(){
int n,k;
scanf("%d %d",&n,&k);
q.push(n);
memset(vis,false,sizeof(vis));
vis[n]=true;
memset(a,0,sizeof(a));
while (!q.empty()) {
int temp = q.front();
q.pop();
//cout<<temp<<endl;
if (temp == k)
break;
int next = temp + 1;
if (!vis[next] && next >= 0 && next < N << 1) {
vis[next] = true;
a[next] = a[temp] + 1;
q.push(next);
}
next = temp - 1;
if (!vis[next] && next >= 0 && next < N << 1) {
vis[next] = true;
a[next] = a[temp] + 1;
q.push(next);
}
next = temp << 1;
if (!vis[next] && next >= 0 && next < N << 1) {
vis[next] = true;
a[next] = a[temp] + 1;
q.push(next);
}
}
printf("%d\n",a[k]);
return 0;
}