Time Limit: 5000/2000 MS
(Java/Others) Memory Limit: 32768/32768 K
(Java/Others)
Total Submission(s): 6383 Accepted
Submission(s): 2034
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
hdu 2717:Catch That Cow(bfs广搜,经典题,一维数组搜索),布布扣,bubuko.com
hdu 2717:Catch That Cow(bfs广搜,经典题,一维数组搜索)
原文:http://www.cnblogs.com/yym2013/p/3649345.html