Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 68998 Accepted: 21707
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题,BFS是宽度优先搜索算法(又称广度优先搜索);
想入门一定要搞懂这题:
要有耐心,我也用了不少时间:
BFS要用到队列,这个知识要必须学会才能更好理解BFS:
代码如下:
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
int n,s,e;
int ss[300000],vis[300000];
struct node
{
int x;
int step;
};
int BFS()
{
queue<node> Q;
node a,next;
int i;
a.x = s;
a.step = 0;
vis[s] = 1;
Q.push(a);
while(!Q.empty())
{
a = Q.front();
Q.pop();
if(a.x == e)
{
return a.step;
}
next = a;
next.x=next.x-1;
if(next.x>=0&&vis[next.x]==0)
{
vis[next.x] = 1;
next.step++;
Q.push(next);
}
next = a;
next.x=next.x+1;
if(next.x<=100000&&vis[next.x]==0)
{
vis[next.x] = 1;
next.step++;
Q.push(next);
}
next = a;
next.x=2*next.x;
if(next.x<=100000&&vis[next.x]==0)
{
vis[next.x] = 1;
next.step++;
Q.push(next);
}
}
return -1;
}
int main()
{
int i,j;
scanf("%d %d",&s,&e);
memset(vis,0,sizeof(vis));
printf("%d\n",BFS());
return 0;
}