poj 3278 Catch That Cow(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 - 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.

 题意:FJ要抓奶牛,输入n(FJ的位置),k(奶牛的位置),求FJ抓到奶牛所需最少时间。

 FJ有三种走法:

    1:向前移动一步,花费一分钟

    2:向后退后一步,花费一分钟

     3:向前移动当前位置的2倍,花费一分钟

 1 #include <iostream>
 2 #include <cstring>
 3 #include <queue>
 4 using namespace std;
 5 const int MAX=100005;
 6 bool vis[MAX];
 7 int step[MAX];
 8 queue <int >q;
 9 int bfs(int n,int k)
10 {
11     int head,next;
12     q.push(n);
13     step[n]=0;
14     vis[n]=true;
15     while(!q.empty())
16     {
17         head=q.front();  //取队首
18         q.pop();
19         for(int i=0; i<3; i++)
20         {
21             if(i==0)
22                 next=head-1;
23             if(i==1)
24                 next=head+1;
25             if(i==2)
26                 next=head*2;
27             if(next<0||next>=MAX)  //排除出界情况
28                 continue;
29             if(!vis[next])
30             {
31                 q.push(next);  //入队
32                 step[next]=step[head]+1;//步数加一
33                 vis[next]=true;  //标记访问
34             }
35             if(next==k)
36                 return step[next];
37         }
38 
39     }
40 }
41 int main()
42 {
43     int n,k;
44     while(cin>>n>>k)
45     {
46         memset(vis,false,sizeof(vis));
47         memset(step,0,sizeof(step));
48         while(!q.empty())
49             q.pop();
50         if(n>=k)
51             cout<<n-k<<endl;
52         else
53             cout<<bfs(n,k)<<endl;
54     }
55     return 0;
56 }
View Code
原文地址:https://www.cnblogs.com/cxbky/p/4844246.html