poj 3278Catch 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.
 
初学bfs最好的题了,比较简单,当初刚学的时候就做了好几遍这个--
View Code
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <queue>
 4 #include <algorithm>
 5 #include <cstdlib>
 6 using namespace std;
 7 const int N=100010;
 8 struct num
 9 {
10     int flag;
11     int step;
12 }p[N];
13 int main()
14 {
15     int n,k;
16     queue<int>q;
17     memset(p,0,sizeof(p));
18     scanf("%d%d",&n,&k);
19     q.push(n);
20     p[n].flag=1;
21     while(!q.empty())
22     {
23         n=q.front();
24         if(n==k)
25             break;
26         q.pop();
27         if((n-1)>=0&&(n-1)<=100000&&p[n-1].flag==0)
28         {
29             q.push(n-1);
30             p[n-1].flag=1;
31             p[n-1].step=p[n].step+1;
32             /*if(n-1==k)
33             {
34                 printf("%d\n",p[n-1].step);
35                 break;
36             }*/
37         }
38         if((n+1)>=0&&(n+1)<=100000&&p[n+1].flag==0)
39         {
40             q.push(n+1);
41             p[n+1].flag=1;
42             p[n+1].step=p[n].step+1;
43             /*if(n+1==k)
44             {
45                 printf("%d\n",p[n+1].step);
46                 break;
47             }*/
48         }
49         if((n*2)>=0&&(n*2)<=100000&&p[n*2].flag==0)
50         {
51             q.push(n*2);
52             p[n*2].flag=1;
53             p[n*2].step=p[n].step+1;
54             /*if(n*2==k)
55             {
56                 printf("%d\n",p[n*2].step);
57                 break;
58             }*/
59         }
60     }
61     printf("%d\n",p[k].step);
62     return 0;
63 }
原文地址:https://www.cnblogs.com/wilsonjuxta/p/2963703.html