catch that cow (bfs 搜索的实际应用,和图的邻接表的bfs遍历基本上一样)

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 38263   Accepted: 11891

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<stdlib.h>
 3 #include<string.h>
 4 struct vode
 5 {
 6     int time,weizhi;
 7 };
 8 struct vode que[100001];
 9 int main()
10 {
11     int l,r,weizhi;
12     int n,k;
13     scanf("%d%d",&n,&k);
14     l=0,r=0;
15     weizhi=n;
16     que[r].weizhi=weizhi;
17     que[r].time=0;
18     r++;
19     int flag[100001]={0};
20     flag[weizhi]=1;
21     while(que[l].weizhi!=k)
22     {
23         weizhi=que[l].weizhi;
24         if(weizhi-1>=0&&weizhi-1<=100000&&flag[weizhi-1]==0)
25         {
26             que[r].weizhi=que[l].weizhi-1;
27             que[r].time=que[l].time+1;
28             flag[weizhi-1]=1;
29             r++;
30         }
31         if(weizhi+1>=0&&weizhi+1<=100000&&flag[weizhi+1]==0)
32         {
33             que[r].weizhi=que[l].weizhi+1;
34             que[r].time=que[l].time+1;
35             flag[weizhi+1]=1;
36             r++;
37         }
38         if(weizhi*2>=0&&weizhi*2<=100000&&flag[weizhi*2]==0)
39         {
40             que[r].weizhi=que[l].weizhi*2;
41             que[r].time=que[l].time+1;
42             flag[weizhi*2]=1;
43             r++;
44         }
45         l++;
46     }
47     printf("%d\n",que[l].time);
48     return 0;
49 }
View Code

 

posted @ 2013-08-12 15:07  狂盗一枝梅  阅读(369)  评论(0编辑  收藏  举报