Catch That Cow
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
Output
4
翻译:
抓住那头牛
Farmer John 已获悉一头逃亡奶牛的位置,并希望立即抓住她。他从数轴上的点N (0 ≤ N ≤ 100,000) 开始,而奶牛在同一数轴上的点K (0 ≤ K ≤ 100,000) 处。Farmer John 有两种交通方式:步行和传送。
- 行走:FJ 可以在一分钟内从任意点 X 移动到点X - 1或X + 1 * 瞬移:FJ 可以在一分钟内从
任意点X移动到点 2 × X。
如果母牛没有意识到它的追赶,根本不动,农夫约翰需要多长时间才能找回它?
输入
第 1 行:两个空格分隔的整数:N和K
输出
第 1 行:Farmer John 捕捉逃亡牛所需的最少时间(以分钟计)。
样本
输入
5 17
输出
4
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int book[1000000];
int n,k;
struct node
{
int x,step;
};
node now,ne,start;
void bfs()
{
queue<node>q;
q.push(start);
while(q.size())
{
now=q.front();
q.pop();
if(now.x==k)
{
cout<<now.step;
return ;
}
for(int i=0; i<3; i++)
{
if(i==0) ne.x=now.x+1;
else if(i==1) ne.x=now.x-1;
else if(i==2) ne.x=now.x*2;
ne.step=now.step+1;
if(book[ne.x]==0&&ne.x>=0&&ne.x<100005)
{
q.push(ne);
book[ne.x]=1;
}
}
}
}
int main()
{
cin>>n>>k;
memset(book,0,sizeof book);
book[n]=1;//这个位置已经走过
start.x=n;//记录起始位置
start.step=0;//起始步数
bfs();
return 0;
}