Catch That Cow
Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Submit Status
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.
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<stack>
using namespace std;
#define N 100010
int time[N], maps[N], s, e;//将这些宏定义是为了避免传参;
void BFS();
int main()
{
while(scanf("%d%d", &s, &e)!=EOF)
{
memset(time, 0, sizeof(time));//定义的时间数组,初始化为零;本身定义了结构体,其中包含了位置location、时间time、标记变量flag。却发现flag无法初始化
memset(maps, 0, sizeof(maps));//标记是否走过
if(s==e)
printf("0\n");
else
BFS();
}
return 0;
}
void BFS()
{
queue<int>que;
int i, x, dir;
maps[s]=1;
que.push(s);
while(!que.empty())
{
x=que.front();
que.pop();
for(i=0; i<3; i++)
{
switch(i)//用switch更简便;
{
case 0: dir=x-1; break;
case 1: dir=x+1; break;
case 2: dir=x*2; break;
}
if(dir==e)//结束条件。其实也可放在for循环外,只不过是多进行了几步而已
{
printf("%d\n", time[x]+1);
return;
}
if(maps[dir]==0&&dir<N&&dir>=0)//这也算是剪枝,减少了重复
{
que.push(dir);
maps[dir]=1;
time[dir]=time[x]+1;
}
}
}
}