Catch That Cow
| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 51790 | Accepted: 16263 |
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
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.
小结:
虽然不是我做的第一道BFS题目,但是是我做过最简单的一道题目,真的要说有什么陷阱的话,感觉有2点:第一,题目明明没说,是测试多组数据(也可能是我没看清楚),但是只有按照多组测试数据来,才能AC,不然WA一辈子;第二,需要注意的就是输入1,0的这组情况,取值范围是闭区间,所以这个输出是有结果的。
恩!大概就是这样啦,发下代码就睡觉了,熬夜刷题的同志们,大家也要注意身体,早点睡觉哦!
以下是AC代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int s,e;
int fun(int a,int x)
{
if(a==1)
return 2*x;
else if (a==2)
return x+1;
else
return x-1;
}
struct node
{
int x,step;
}point[120000];
int vis[120000];
int bfs()
{
struct node temp;
int top,end;
temp.x=s;
vis[s]=1;
temp.step=0;
top=end=0;
point[top]=temp;
while(top>=end)
{
temp=point[end];
end++;
for(int i=1;i<=3;i++)
{
struct node t;
t=temp;
t.x=fun(i,t.x);
t.step++;
if(t.x>100000||vis[t.x]||t.x<0)
continue;
if(t.x==e)
return t.step;
else
{
//printf("\n%d\n",t.x);
point[++top]=t;
vis[t.x]=1;
}
}
}
return 0;
}
int main()
{
while(~scanf("%d%d",&s,&e))
{
memset(vis,0,sizeof(vis));
printf("%d\n",bfs());
}
return 0;
}
#include<string.h>
#include<stdlib.h>
#include<math.h>
int s,e;
int fun(int a,int x)
{
if(a==1)
return 2*x;
else if (a==2)
return x+1;
else
return x-1;
}
struct node
{
int x,step;
}point[120000];
int vis[120000];
int bfs()
{
struct node temp;
int top,end;
temp.x=s;
vis[s]=1;
temp.step=0;
top=end=0;
point[top]=temp;
while(top>=end)
{
temp=point[end];
end++;
for(int i=1;i<=3;i++)
{
struct node t;
t=temp;
t.x=fun(i,t.x);
t.step++;
if(t.x>100000||vis[t.x]||t.x<0)
continue;
if(t.x==e)
return t.step;
else
{
//printf("\n%d\n",t.x);
point[++top]=t;
vis[t.x]=1;
}
}
}
return 0;
}
int main()
{
while(~scanf("%d%d",&s,&e))
{
memset(vis,0,sizeof(vis));
printf("%d\n",bfs());
}
return 0;
}
本文介绍了一个简单的广度优先搜索(BFS)算法应用案例——《CatchThatCow》。问题描述了农夫约翰如何通过步行和瞬移的方式,在最短时间内抓住静止不动的逃逸奶牛。文章分享了AC代码,并提到了实现过程中需要注意的细节。
474

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



