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<string.h>
#include<queue>
using namespace std;
int main()
{
int n,k,m,v[100005];
while(cin>>n>>k)
{ memset(v,0,sizeof(v));
m=0;
if(n>=k)
cout<<n-k<<endl;
else { queue<int>q;
q.push(n);
v[n]=1;
q.push(m);
while(!q.empty())
{
n=q.front();
q.pop();
m=q.front();
q.pop();
if(n==k) break;
if(n+1<100005&&v[n+1]!=1)
{
q.push(n+1);
v[n+1]=1;
q.push(m+1);
}
if(n-1>=0&&v[n-1]!=1)
{
q.push(n-1);
v[n-1]=1;
q.push(m+1);
}
if(2*n<100005&&v[2*n]!=1)
{
q.push(2*n);
v[2*n]=1;
q.push(m+1);
}
}
cout<<m<<endl;
}
}
}

被折叠的 条评论
为什么被折叠?



