题目描述:
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?
Input5 17
4
using namespace std;
int m,n;
int dr[ 2]={ 1, -1}; //前进和后退一步
int bj[s];
struct st
{
int x; //记录当前位置
int t; //记录搜索次数
};
int bfs(int a){
int i,dx;
memset(bj, 0, sizeof(bj));
queue<st> qu;
st now,ne;
now.x=a,now.t= 0;
qu.push(now);
bj[a]= 1; //标记初始搜索基点
while(!qu.empty())
{
now=qu.front();
qu.pop();
if(now.x==n)
return now.t; //搜索到目标点返回搜索次数
else
{
for(i= 0;i< 2;i++) //搜索前进一步和后退一步的点
{
dx=now.x+dr[i];
if(dx>= 0&&dx<= 100000) //不能超过题目限制
{
ne.x=dx;
ne.t=now.t;
if(dx==n)
return now.t+ 1;
if(bj[dx]== 0)
{
ne.t++;
qu.push(ne);
bj[dx]= 1;
}
}
}
dx=now.x* 2; //搜索前进2倍的点
if(dx>= 0&&dx<= 100000)
{
ne.x=dx;
if(dx==n)
return now.t+ 1;
ne.t=now.t;
if(bj[dx]== 0)
{
ne.t++;
qu.push(ne);
bj[dx]= 1;
}
}
}
}
}
int main() {
int i,j,sum,a,b;
scanf( "%d%d",&m,&n);
if(m>=n) //此时只能后退一步
printf( "%d\n",m-n);
else
{
sum=bfs(m);
printf( "%d\n",sum);
}
return 0;
}