| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 43653 | Accepted: 13605 |
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
#include<stdio.h> #include<string.h> int front,rear,visit[100001],bu[100001],m,n; typedef struct { int w; }sqtype; sqtype sq[100001]; void bfs() { int x; front=rear=0; sq[0].w=m; bu[m]=0; visit[m]=1; while(front<=rear) { x=sq[front].w; if(visit[n]!=0) break; if(x-1>=0&&visit[x-1]==0) { rear++; sq[rear].w=x-1; bu[x-1]=bu[x]+1; visit[x-1]=1; } if(x+1<=100001&&visit[x+1]==0) { rear++; sq[rear].w=x+1; bu[x+1]=bu[x]+1; visit[x+1]=1; } if(x*2<=100001&&visit[x*2]==0) { rear++; sq[rear].w=x*2; bu[x*2]=bu[x]+1; visit[x*2]=1; } front++; } } main() { scanf("%d%d",&m,&n); memset(visit,0,sizeof(visit)); bfs(); printf("%d",bu[n]); }

本文介绍了一个有趣的算法问题——抓逃逸的牛。农夫约翰利用步行和瞬移两种方式,在数轴上寻找并抓住静止不动的牛。通过广度优先搜索算法(BFS),文章详细展示了如何计算出农夫约翰捕捉到牛所需的最短时间。

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



