BFS宽度优先搜索

D - Catch That Cow
Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

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.
 
 
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<queue>
 4 using namespace std;
 5 #define N 100001
 6 bool s[N];
 7 struct node
 8 {
 9     int x,time;
10 };
11 bool limit(int x)
12 {
13     if(x>=0&&x<=100000)
14         return true;
15     else return false;
16 }
17 void bfs(int n,int k)
18 {
19     queue<node> q;
20     node a,b;
21     memset(s,false,sizeof(s));
22     a.x=n;a.time=0;
23     s[n]=true;
24     q.push(a);
25     while(!q.empty())
26     {
27         a=q.front();
28         q.pop();
29         if(a.x==k)
30         {
31             printf("%d\n",a.time);
32             return ;
33         }
34         if(limit(a.x*2)&&!s[a.x*2])
35         {
36             b.x=a.x*2;
37             b.time=a.time+1;
38             s[a.x*2]=true;
39             q.push(b);
40         }
41         if(limit(a.x-1)&&!s[a.x-1])
42            {
43                b.x=a.x-1;
44                b.time=a.time+1;
45                s[a.x-1]=true;
46                q.push(b);
47            }
48           if(limit(a.x+1)&&!s[a.x+1])
49           {
50               b.x=a.x+1;
51               b.time=a.time+1;
52               s[a.x+1]=true;
53               q.push(b);
54           }
55     }
56 }
57 int main()
58 {
59     int n,k;
60     while(scanf("%d%d",&n,&k)!=EOF)
61     {
62         bfs(n,k);
63     }
64     return 0;
65 }

 

posted @ 2015-05-24 18:12  dongq  阅读(226)  评论(0编辑  收藏  举报