poj 3278 BFS

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 30928   Accepted: 9537

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.
 

一般的广搜,不过要考虑的就是不要让数组越界
 
代码:
View Code
 1 #include <iostream>

 2 #include <stdio.h>

 3 #include <string.h>

 4 using namespace std;

 5 

 6 struct M{

 7     int add;

 8     int step;

 9 };

10 

11 M queue[2000005];

12 bool vis[2000005]={false};

13 

14 int BFS(int s, int e)

15 {

16     

17     int head=0;

18     int tail=0;

19     queue[0].add=s;

20     queue[tail++].step=0;

21     while(head<tail)

22     {

23         M x=queue[head++];

24         if(x.add==e)

25         {

26             return x.step;

27         }

28         if(!vis[x.add+1])

29         {

30             vis[x.add+1]=true;

31             queue[tail].add=x.add+1;

32             queue[tail++].step=x.step+1;

33         }

34         if( x.add-1>=0 && !vis[x.add-1])    //x.add-1>=0 这个不要忘了,不然会runtime error

35         {

36             vis[x.add-1]=true;

37             queue[tail].add=x.add-1;

38             queue[tail++].step=x.step+1;

39         }

40         if(!vis[x.add*2] && x.add*2<=200000)  // 同样的,add*2<=200000也是必须的,否则由于广搜,会乘到很大。

41         {

42             vis[x.add*2]=true;

43             queue[tail].add=x.add*2;

44             queue[tail++].step=x.step+1;

45         }

46     }

47     return 0;

48 }

49 

50 int main()

51 {

52     int N,K;

53     int i,j;

54     while(scanf("%d%d",&N,&K)!=EOF)

55     {

56         printf("%d\n",BFS(N,K));

57     }

58     return 0;

59 }

 

你可能感兴趣的:(poj)