hdu 2717:Catch That Cow(bfs广搜,经典题,一维数组搜索)
Catch That Cow
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6383 Accepted Submission(s): 2034
Problem 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?
* 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.
Source
Recommend
bfs搜索题,基础题。
很简单的一道bfs搜索题,只不过把常见的二维地图换成了一维的,由于是生题,一开始想复杂了,注意剪枝,普通的广搜思路就能过。
代码:
1 #include <stdio.h>
2 #include <string.h>
3 #include <queue>
4 using namespace std;
5 bool isw[100010];
6 int step[100010];
7 void bfs(int n,int k)
8 {
9 memset(isw,0,sizeof(isw));
10 queue <int> q;
11 int cur,next;
12 cur = n;
13 step[n] = 0;
14 isw[cur] = true;
15 q.push(cur);
16 while(!q.empty()){
17 cur = q.front();
18 q.pop();
19 if(cur==k) //找到,返回结果
20 return ;
21 int i;
22 for(i=1;i<=3;i++){ //步行,或者传送
23 switch(i){
24 case 1:
25 next = cur - 1;
26 if(isw[next]) //剪枝,走过的不能走
27 break;
28 if(next<0 || next>100010) //剪枝,越界不能再走
29 break;
30 step[next] = step[cur] + 1;
31 q.push(next);
32 isw[next] = true;
33 break;
34 case 2:
35 next = cur + 1;
36 if(isw[next])
37 break;
38 if(next<0 || next>100010)
39 break;
40 step[next] = step[cur] + 1;
41 q.push(next);
42 isw[next] = true;
43 break;
44 case 3:
45 next = cur * 2;
46 if(isw[next])
47 break;
48 if(next<0 || next>100010)
49 break;
50 step[next] = step[cur] +1;
51 q.push(next);
52 isw[next] = true;
53 break;
54 }
55 }
56 }
57 }
58 int main()
59 {
60 int n,k;
61 while(scanf("%d%d",&n,&k)!=EOF){
62 bfs(n,k);
63 printf("%d\n",step[k]);
64 }
65 return 0;
66 }
Freecode : www.cnblogs.com/yym2013