【搜索】POJ3278: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 pointN(0 ≤N≤ 100,000) on a number line and the cow is at a pointK(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 pointXto the pointsX- 1 orX+ 1 in a single minute
* Teleporting: FJ can move from any pointXto the point 2 ×Xin 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:NandK
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 <iostream>
2 #include <cstdio>
3 #include <algorithm>
4 #include <cstring>
5 #include <queue>
6 using namespace std;
7 const int maxn = 100010;
8 bool vis[maxn];
9 int step[maxn];
10
11 bool bound(int num)
12 {
13 if(num<0||num>100000)
14 return true;
15 return false;
16 }
17 int bfs(int sta,int endd)
18 {
19 queue<int> q;
20 int now,nextt;
21 q.push(sta);
22 vis[sta]=true;
23 while(!q.empty())
24 {
25 now=q.front();
26 q.pop();
27 for(int i=0;i<3;i++)
28 {
29 if(i==0)
30 nextt=now+1;
31 else if(i==1)
32 nextt=now-1;
33 else
34 nextt=now*2;
35 if(bound(nextt))
36 continue;
37 if(!vis[nextt])
38 {
39 step[nextt]=step[now]+1;
40 if(nextt==endd)
41 return step[nextt];
42 vis[nextt]=true;
43 q.push(nextt);
44 }
45 }
46 }
47 }
48 int main()
49 {
50 int sta,endd;
51 while(scanf("%d%d",&sta,&endd)!=EOF)
52 {
53 memset(vis,false,sizeof(vis));
54 if(sta>=endd)
55 printf("%d\n",sta-endd);
56 else
57 {
58 int ans=bfs(sta,endd);
59 printf("%d\n",ans);
60 }
61 }
62 return 0;
63 }View Code