POJ 3278 Catch That Cow

这题算是比较简单的广搜题,每次有三种决策,可添加一些剪枝加快速度,直接看代码吧:

 1 #include <iostream>
2 #define MAX 200001
3 using namespace std;
4 int n, k;
5 bool vis[MAX];//记录某点是否被走过
6 int queue[MAX], time[MAX];

7 int bfs()
8 {
9 int front = 0, rear = 1;
10 int x, temp;
11 queue[front] = n; vis[n] = true;//把起点放入队列的头部
12 while(front < rear)

13 {
14 x = queue[front]; temp = time[front];
15 if(x == k)//找到最优解
16 return temp;

17 if(!vis[x - 1] && x - 1 > 0)//也算是一种剪枝
18 {

19 vis[x - 1] = true;
20 time[rear] = temp + 1;
21 queue[rear++] = x - 1;
22 }
23 if(!vis[x + 1] && x + 1 <= k)
24 {
25 vis[x + 1] = true;
26 time[rear] = temp + 1;
27 queue[rear++] = x + 1;
28 }
29 if(!vis[x * 2 ] && x * 2 <= 100000 && x > 0)
30 {
31 vis[x * 2] = true;
32 time[rear] = temp + 1;
33 queue[rear++] = x * 2;
34 }
35 front ++;
36 }
37 }
38 int main()
39 {
40 while(cin >> n >> k)
41 {
42 int ans;
43 memset(vis, false, sizeof(vis));
44 memset(queue, 0, sizeof(queue));
45 memset(time, 0, sizeof(time));
46 if(n >= k)//要考虑起点比终点还远的情况
47 ans = n - k;

48 else
49 ans = bfs();
50 printf("%d\n", ans);
51 }
52 return 0;
53 }



posted @ 2012-02-24 10:55  背着超人飞  阅读(151)  评论(0)    收藏  举报