POJ 3278第一道BFS,此题刚开始做是纠结了很久,毕竟是第一道要用到队列又赶紧把队列看了一遍,经过几次WA后左后总算AC了

 1 #include<iostream>
2 #include<queue>
3 #define MAXV 100000
4 using namespace std;
5 int sign[100001],len[100001]; //sign是用来做标记的,len用来走到重点需步长
6 int main()
7 {
8 int N, K, y;
9 cin >> N >> K;
10 queue<int>Q;
11 Q.push(N);
12 len[N] = 0;
13 while(!Q.empty())
14 {
15 y = Q.front();
16 Q.pop();
17 sign[y] = 1;
18 if (y == K) break;
19 else
20 {
21 if (sign[y-1]==0 && y>=1)
22 {
23 Q.push(y-1);
24 len[y-1] = len[y] + 1;
25 sign[y-1] = 1;
26 }
27 if (y+1<=MAXV && sign[y+1]==0)
28 {
29 Q.push(y+1);
30 len[y+1] = len[y] + 1;
31 sign[y+1] = 1;
32 }
33 if (2*y<=MAXV && sign[2*y]==0)
34 {
35 Q.push(2*y);
36 len[2*y] = len[y] + 1;
37 sign[2*y] = 1;
38 }
39 }
40 }
41 cout<<len[y]<<endl;
42 return 0;
43 }
44
posted @ 2011-08-19 17:23  zhongya  阅读(146)  评论(0编辑  收藏  举报