Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K |
Total Submissions: 89208 | Accepted: 27970 |
Description
Farmer John has been informed of the location of afugitive cow and wants to catch her immediately. He starts at a pointN(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 oftransportation: walking and teleporting.
* Walking: FJ can move from any point X to thepoints X - 1 orX + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X ina single minute.
If the cow, unaware of its pursuit, does not move atall, how long does it take for Farmer John to retrieve it?
Input
Line 1: Two space-separated integers: N andK
Output
Line 1: The least amount of time, in minutes, it takesfor Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitivecow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
简要题意:
有一个农夫和一头牛,在一个数轴上,位置用整数N,K表示。农夫有三种移动方式,从位置为N可以移动到N-1、N+1、和2N的位置,每种方式耗时均为单位时间1,牛固定在自己的位置不移动,求农夫抓到牛所用的最短时间。
分析:把数轴可以看作一个有向图,每个整数视作一个顶点,相邻整数之间互相连通,而N只能单向连通2N,用bfs搜索最短路径即可。注意标记每个顶点是否被访问过,被访问过后不需要再次访问,否则不是最优解。
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <math.h>
using namespace std;
//bfs搜索
struct point
{
int x; //记录当前位置
int step; //记录步数
point(int xx,int ss):x(xx),step(ss){}; //初始化
};
const int MAXN=200000+5;
bool vis[MAXN]; //标记每个顶点
queue <point> temp;
int main()
{
int N,K;
scanf("%d %d",&N,&K);
temp.push(point(N,0));
memset(vis,false,sizeof(vis));
while(!temp.empty())
{
point cur=temp.front();
vis[cur.x]=true; //访问该点
if(cur.x==K) //到达目的点,返回答案
{
printf("%d\n",cur.step);
break;
}
if(cur.x-1>=0 && !vis[cur.x-1]) //注意越界判断,把三种方式压入队列中
temp.push(point(cur.x-1,cur.step+1));
if(cur.x+1<=100000 && !vis[cur.x+1])
temp.push(point(cur.x+1,cur.step+1));
if(cur.x*2<=100000 && !vis[cur.x*2])
temp.push(point(cur.x*2,cur.step+1));
temp.pop(); //弹出队首元素
}
return 0;
}