题目描述
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?
输入
Line 1: Two space-separated integers: N and K
输出
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
题解:这个问题就是优先遍历节点周围的x-1,x+1,x+2。这三个节点能否满足条件,如果不满足就在这三个节点中在进行前面方式的遍历,直到找到为止。
示例输入
5 17
示例输出
4
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
struct node
{
int data;
int time;
};
queue<struct node> qu;
int vis[200001];//这个内存开到要求的双倍。
int Bfs(int n,int m)
{
int i;
memset(vis,0,sizeof(vis));
while(!qu.empty())
qu.pop();
struct node current,next;//先把第一个节点入队列
current.data=n;
vis[current.data]=1;
current.time=0;
qu.push(current);
while(!qu.empty())
{
current=qu.front();
qu.pop();
for(i=1; i<=3; i++)
{
if(i==1)
next.data=current.data-1;//在这里遍历节点周围的三个节点,如果不满足条件,节点入队列。
else if(i==2)
next.data=current.data+1;
else
next.data=current.data*2;
next.time=current.time+1;//记得时间加一。
if(next.data==m)
return next.time;
if(!vis[next.data]&&next.data>=0&&next.data<=100000)
{
qu.push(next);
vis[next.data]=1;//标记节点,已经如果队列的节点,就不在入队列了。
}
}
}
return 0;
}
int main()
{
int n,m;
cin>>n>>m;
if(n>=m)
{
cout<<n-m<<endl;
}
else
{
Bfs(n,m);
cout<<Bfs(n,m)<<endl;
}
return 0;
}