POJ3287(BFS水题)

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.
题意:

FJ要抓奶牛。

开始输入N(FJ的位置)K(奶牛的位置)。

FJ有三种移动方法:1、向前走一步,耗时一分钟。

2、向后走一步,耗时一分钟。

3、向前移动到当前位置的两倍N*2,耗时一分钟。

问FJ抓到奶牛的最少时间(奶牛不动)

解题思路:很明显我们求最短的时间就相当于求走的最少步数,所以我们就很容易想到用广搜BFS了,把每次FJ可以到的位置都压入队列,然后用一个vis数组标记FJ是否已经去过该位置了,再用 一个step数组存储FJ到该位置所需要的最短时间即可。要注意的是,他的位置也有范围是0-100000,开始我就是因为右区间少了个=号,WA了好几次,所以还是要细心。难的做不出只好做简单的了。。。

附上代码:

 #include<iostream>
#include<cstdio>
#include<string.h>
#include<queue>
using namespace std;
int vis[]; //标记是否走过
int step[]; //储存到该处的最短时间
int n,k;
queue<int> que;
int ans; int BFS()
{
que.push(n);
step[n]=;
vis[n]=;
while(que.size())
{
int p=que.front();
que.pop();
if(p==k) break;
for(int i=;i<;i++)
{
int dx;
if(i==) dx=p-;
if(i==) dx=p+;
if(i==) dx=*p;
if(dx>=&&dx<=&&vis[dx]==)
{
que.push(dx);
step[dx]=step[p]+;
vis[dx]=;
} }
}
return step[k];
} int main()
{
while(cin>>n>>k)
{
memset(vis,,sizeof(vis));
memset(step,,sizeof(step));
ans=BFS();
cout<<ans<<endl;
}
return ;
}
上一篇:hdu-------(1698)Just a Hook(线段树区间更新)


下一篇:phpstorm 2016.2 的最新破解方法(截止2016-8-1)