Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 27816 | Accepted: 8556 |
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.
Source
解题报告:
这道题其实挺简单的,但是好久没有写搜索题了,很不细心,
,哎!这道题的题意:就是在一条数轴上,求起始点到终点的最小步数,很显然得用BFS借助于队列;
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000010;
int visit[2 *N], queue[2 * N], step[2 * N], ans;//queue起到队列的作用
void BFS(int begin, int end)
{
int rear, front, a, b[3], i;
rear = 0;//队列的尾
front = 0;//队列的头
rear ++;
queue[rear] = begin;//初始化
while (front < rear)
{
front ++;
a = queue[front];
if (a == end)//找到
{
ans = step[a];
return ;
}
else
{
b[0] = a + 1;
b[1] = a - 1;
b[2] = 2 * a;
for (i = 0; i <=2; ++i)
{
if (b[i] >= 0 && b[i] <= 1000000 && !visit[b[i]])//当时写的时候1000000写成了100000少写了一个零,Runtime Error好几次!!
{
visit[b[i]] = 1;//标记
rear ++;
queue[rear] = b[i];//插到队尾
step[b[i]] = step[a] + 1;//步数加1
}
}
}
}
}
int main()
{
int begin, end;
while (scanf("%d%d", &begin, &end) != EOF)
{
memset(visit, 0, sizeof(visit));
memset(queue, 0, sizeof(queue));
memset(step, 0, sizeof(step));
visit[begin] = 1;
BFS(begin, end);
printf("%d\n", ans);
}
return 0;
}
,哎!这道题的题意:就是在一条数轴上,求起始点到终点的最小步数,很显然得用BFS借助于队列;
代码如下: