B - Catch That Cow

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 - 1 or + 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.
 
 
 
 
AC代码:
 #include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
bool used[1000001];//记录经过的点,bool的头文件为string
int vis[1000001];//记录时间
int bfs(int s,int e)//s为起点,e为终点
{
queue<int> q;//头文件为queue
int pos=s;
used[pos]=true;
vis[pos]=0;//起始时时间为零
q.push(pos);//栈初始化
while(!q.empty())
{
pos=q.front();//检索栈顶元素
q.pop();//出栈
if(pos==e) return vis[pos];//特殊情况当起点就是终点时,返回0
if(pos+1<=100000&&!used[pos+1])//判断是否可执行
{
used[pos+1]=true;//没走过的点就赋为一
vis[pos+1]=vis[pos]+1;
q.push(pos+1);//探索完后入栈
}
if(pos-1>0&&!used[pos-1])
{
used[pos-1]=true;
vis[pos-1]=vis[pos]+1;
q.push(pos-1);
}
if(pos*2<=100000&&!used[pos*2])
{
used[pos*2]=true;
vis[pos*2]=vis[pos]+1;
q.push(pos*2);
}
}
return 0;
}
int main()
{
int i,j;
while(scanf("%d%d",&i,&j)!=EOF)//输入多组数据
{
memset(used,false,sizeof(used));//清零
cout<<bfs(i,j)<<endl;
}
return 0;
}
分析:就是一个人通过三种不同的走法,要你结合每一种走法求出从起点到终点的最短步数
思路:用栈和BFS解决,首先将队列初始化,然后当栈非空的时候,考虑特殊情况,接着就进行每一种走法的判断。
心得:通过做此题加深了我对栈和BFS的认知,另外学会了一个新函数的使用,即memset函数(用来为数据清零,头文件为string);做题时我们要从整体往局部写,先写一个大的框架,再添细节,但我很明显还没有习惯这么做,以后做题要注意这方面的培养,这样会让你做题更加简单。
 
 
 
posted @ 2016-07-16 14:29  踮起脚望天  阅读(703)  评论(2编辑  收藏  举报