POJ 3275 Catch That Cow(bfs)

Catch 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 X - 1 or X + 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<cstdio>
 2 #include<queue>
 3 #include<cstring>
 4 using namespace std;
 5 
 6 const int maxn=200050;
 7 int N,K;
 8 int vis[maxn];
 9 
10 struct point
11 {
12     int pos;
13     int step;
14 };
15 
16 int bfs()
17 {
18     queue<point>q;
19     point init;
20     init.pos=N;
21     init.step=0;
22     q.push(init);
23     vis[N]=1;
24     while(!q.empty())
25     {
26         point node=q.front();
27         q.pop();
28         if(node.pos==K)
29         return node.step;
30         point newnode1,newnode2,newnode3;
31         newnode1.pos=node.pos-1;
32         newnode2.pos=node.pos+1;
33         newnode3.pos=node.pos*2;
34         newnode1.step=newnode3.step=newnode2.step=node.step+1;
35         if(!vis[newnode1.pos])
36         {
37             vis[newnode1.pos]=1;
38             q.push(newnode1);
39         }
40         if(!vis[newnode2.pos])
41         {
42             vis[newnode2.pos]=1;
43             q.push(newnode2);
44         }
45         if(newnode3.pos<maxn&&newnode3.pos>=0)
46         if(!vis[newnode3.pos])
47         {
48             vis[newnode3.pos]=1;
49             q.push(newnode3);
50         }
51     }
52 }
53 
54 int main()
55 {
56     while(scanf("%d%d",&N,&K)!=EOF)
57     {
58         memset(vis,0,sizeof(vis));
59         if(N>K)
60         printf("%d
",N-K);
61         else
62         {
63             int ans=bfs();
64             printf("%d
",ans);
65         }
66     }
67     return 0;
68 }
 
原文地址:https://www.cnblogs.com/homura/p/4705876.html