题目链接:传送门
Problem 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
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
题目大意:给出两个坐标s,w。s在数轴上的行走规律是可以向左走一步,向右走一步,或跳到是当前坐标位置的2倍的地方,而且这三种行走情况所消耗的时间都是一秒。求s到达w的最短时间。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
int m[1000010];
int s,w;
struct nm
{
int nat,tim;
};
int bfs()
{
int a,b,c,d;
nm next,tur;
queue<nm>n;
tur.nat=s;
tur.tim=0;
n.push(tur);
m[s]=1;
while(!n.empty())
{
tur=n.front();
n.pop();
if(tur.nat==w)
return tur.tim;
if(m[tur.nat-1]==0&&(tur.nat-1)>=0&&(tur.nat-1)<=100010)
{
next.nat=tur.nat-1;
next.tim=tur.tim+1;
n.push(next);
m[tur.nat-1]=1;
}
if(m[tur.nat+1]==0&&(tur.nat+1)>=0&&(tur.nat+1)<=100010)
{
next.nat=tur.nat+1;
next.tim=tur.tim+1;
n.push(next);
m[tur.nat+1]=1;
}
if(m[tur.nat*2]==0&&(tur.nat*2)>=0&&(tur.nat*2)<=100010)
{
next.nat=tur.nat*2;
next.tim=tur.tim+1;
n.push(next);
m[tur.nat*2]=1;
}
}
return -1;
}
int main()
{
int a;
while(cin>>s>>w)
{
memset(m,0,sizeof(m));
a=bfs();
cout<<a<<endl;
}
return 0;
}