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
Hint
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.
题目大意: 给定两个整数n和k,通过 n+1或n-1 或n*2 这3种操作,使得n==k
求出最少的操作次数
思路:简单的BFS,注意没走一步都要判断在合适的范围之内即可
#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
using namespace std;
//数共有有100001个
const int MAX=100001;
int start,end;
bool visit[MAX];//点的访问标记
int step[MAX];//记录步数
//检查点是否越界(越界1反之0)
int check(int dot){
if(dot<0 || dot>100000){
return 1;
}else if(visit[dot]){
return 1;
}
return 0;
}
int BFS(void){
//起始点大于等于结束点时直接返回(此时只能退着一步一步走)
if(start>=end){
return start-end;
}
queue<int> Q;
memset(visit,false,sizeof(visit));
Q.push(start);
visit[start]=true;//已访问
step[start]=0;//初始步数0
while(!Q.empty()){
int tem = Q.front();
Q.pop();
if(tem == end){//结束
return step[tem];
}
if(!check(tem-1)){//退一步
step[tem-1]=step[tem]+1;
Q.push(tem-1);
visit[tem-1]=true;
}
if(!check(tem+1)){//加一步
step[tem+1]=step[tem]+1;
Q.push(tem+1);
visit[tem+1]=true;
}
if(!check(tem*2)){//进二倍
step[tem*2]=step[tem]+1;
Q.push(tem*2);
visit[tem*2]=true;
}
}
}
int main(void){
while(scanf("%d %d",&start,&end)!=EOF){
cout<<BFS()<<endl;
}
return 0;
}