POJ 3278 Catch That Cow

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <queue>
 5 #define CL(x, y) memset(x,y,sizeof(x))
 6 using namespace std;
 7 const int MAX = 200005;//100005太小了??use[]越界
 8 int a, b, i, j, temp;
 9 int used[MAX];
10 void BFS(int x, int y);
11 struct node
12 {
13     int num;
14     int step;
15 };
16 queue <node> Q;
17 int main()
18 {
19     while(cin >> a >> b)
20     {
21         CL(used, 0);
22         BFS(a, b);
23     }
24     return 0;
25 }
26 void BFS(int front, int rear)
27 {
28     while(!Q.empty())
29         Q.pop();//Q.clear();清空
30     node first, cur, next;
31     first.num = front;
32     first.step = 0;
33     used[front] = 1;
34     Q.push(first);
35     while(!Q.empty())
36     {
37         cur = Q.front();
38         Q.pop();
39         if(cur.num == rear)
40         {
41             cout << cur.step << endl;
42             return ;
43         }
44         for(j = 0; j < 3; j++)
45         {
46             if(j == 0)
47                 temp = cur.num-1;
48             else if(j == 1)
49                 temp = cur.num+1;
50             else
51                 temp = cur.num*2;
52             //            cout << temp << endl;
53             if(!used[temp] && temp>=0 && temp <= 100000)
54             {
55                 next.num = temp;
56                 next.step = cur.step+1;
57                 used[temp] = 1;
58 //                cout << next.num << " " << next.step << endl;
59                 Q.push(next);
60                 Q.push(next);
61             }
62         }
63     }
64 }
View Code

Runtime Error可能是数组过小,特别是used[]数组,最后一定不可以越界

posted @ 2015-03-09 12:47  PastLIFE  阅读(133)  评论(0编辑  收藏  举报