码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3278 Catch That Cow

时间:2015-10-04 14:45:07      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

解题思路:简单宽搜,关键是剪枝。

技术分享
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<queue>
 5 using namespace std;
 6 const int maxn = 100005;
 7 int vis[maxn]; //标记这个点是否走过
 8 int n, k;
 9 
10 
11 struct node{
12     int x, cnt;
13 }p, now;
14 
15 queue<node> q;
16 
17 int bfs(int x, int cnt)
18 {
19     memset(vis, 0, sizeof(vis)); //初始化为没走过
20     while(!q.empty()) q.pop();
21     p.x = x, p.cnt = cnt;
22     q.push(p);
23 
24     while(!q.empty())
25     {
26         p = q.front();
27         q.pop();
28 
29         if(p.x == k) return p.cnt; //走到该点,直接返回步数
30 
31         now.x = p.x + 1, now.cnt = p.cnt + 1;
32         if(now.x <= 100000 && !vis[now.x]) //关键剪枝,没走过并且在符合题目的数据范围之内
33         {
34             vis[now.x] = 1; //标记为已经走过
35             q.push(now);
36         }
37 
38         now.x = p.x - 1, now.cnt = p.cnt + 1;
39         if(now.x >= 0 && !vis[now.x])
40         {
41             vis[now.x] = 1;
42             q.push(now);
43         }
44 
45         now.x = 2 * p.x, now.cnt = p.cnt + 1;
46         if(now.x <= 100000 && !vis[now.x])
47         {
48             vis[now.x] = 1;
49             q.push(now);
50         }
51     }
52     return -1; //不会走到这一步
53 }
54 
55 int main()
56 {
57     while(~scanf("%d %d", &n, &k))
58     {
59         int ans = bfs(n, 0);
60         printf("%d\n", ans);
61     }
62     return 0;
63 }
View Code

 

POJ 3278 Catch That Cow

标签:

原文地址:http://www.cnblogs.com/loveprincess/p/4854479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!