POJ3278 BFS
题目内容
Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 26330 Accepted: 8122
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.
Source
USACO 2007 Open Silver
很纠结的题,算法没有错误却不断WA,最后改成C++编译器AC。错误应该出现在STL的queue里,具体不知。。。手动模拟队列AC。
代码如下(只能用C++编译):
View Code
1 #include<cstdio>
2
3 #include<cstring>
4
5 #include<queue>
6
7 #define MAXN 100001
8
9 using namespace std;
10
11 long n,k;
12
13 bool visited[MAXN];
14
15 long step[MAXN];
16
17 long bfs(long start)
18
19 {
20
21 queue<long>q;
22
23 q.push(start);
24
25 visited[start]=true;
26
27 long ns,t;
28
29 while(!q.empty())
30
31 {
32
33 ns=q.front();
34
35 q.pop();
36
37 if(ns==k)
38
39 return step[ns];
40
41 t=ns+1;
42
43 if(t>=0&&t<=100000&&visited[t]==false)
44
45 {
46
47 step[t]=step[ns]+1;
48
49 if(t==k)
50
51 return step[t];
52
53 visited[t]=true;
54
55 q.push(t);
56
57 }
58
59 t=ns-1;
60
61 if(t>=0&&t<=100000&&visited[t]==false)
62
63 {
64
65 step[t]=step[ns]+1;
66
67 if(t==k)
68
69 return step[t];
70
71 visited[t]=true;
72
73 q.push(t);
74
75 }
76
77 t=ns*2;
78
79 if(t>=0&&t<=100000&&visited[t]==false)
80
81 {
82
83 step[t]=step[ns]+1;
84
85 if(t==k)
86
87 return step[t];
88
89 visited[t]=true;
90
91 q.push(t);
92
93 }
94
95 }
96
97 }
98
99 void init()
100
101 {
102
103 memset(visited,false,sizeof(visited));
104
105 memset(step,0,sizeof(step));
106
107 }
108
109 int main(void)
110
111 {
112
113 while(scanf("%ld%ld",&n,&k)==2)
114
115 {
116
117 init();
118
119 printf("%ld\n",bfs(n));
120
121 }
122
123 return 0;
124
125 }
posted on 2011-10-30 15:41 SilVeRyELF 阅读(246) 评论(0) 收藏 举报

浙公网安备 33010602011771号