概述
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
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
解题思路:
就是普通的广搜模板。但是要注意used和step数组不能只开到100,000,因为还有×2这样的运算,所以保险起见开到1,000,000比较好。判断一个新的位置是否要加入队列不光要看有没有来过这个位置,还要看它是否大于0小于1,000,000。最后就是n=k的特殊情况也要特殊考虑。
#include<stdio.h>
#include<queue>
using namespace std;
queue<int> road;
int n,k;
int used[1000000]={0},step[1000000];
void init();
int bfs();
int main()
{
scanf("%d%d",&n,&k);
if(n==k)
{
printf("0n");
return 0;
}
init();
printf("%dn",bfs());
}
void init()
{
road.push(n);
used[n]=1;
step[n]=0;
}
int bfs()
{
int old,now,i;
while(road.empty()==false)
{
old=road.front();
road.pop();
for(i=1;i<=3;i++)
{
if(i==1)
{
now=old*2;
}
else if(i==2)
{
now=old+1;
}
else
{
now=old-1;
}
if(now==k)
{
return step[old]+1;
}
if(now>0&&now<1000000&&used[now]==0)
{
road.push(now);
used[now]=1;
step[now]=step[old]+1;
}
}
}
}
最后
以上就是尊敬大门为你收集整理的//广搜Bfs简单题//Catch That Cow------三N的全部内容,希望文章能够帮你解决//广搜Bfs简单题//Catch That Cow------三N所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复