hdu2717Catch That Cow 简单BFS

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

刚开始思路错了,用的DP,一直WA,后来才发现是搜索,还是简单的BFS,顿时。。。。

思路:

BFS 三个方向即可;

代码:

 1 #include<iostream>
 2 #include<cstdlib>
 3 #include<cstdio>
 4 #include<cmath>
 5 #include<cstring>
 6 #include<fstream>
 7 #include<queue>
 8 #define MAX 100010
 9 using namespace std;
10 int n,k;
11 int  cur,next;
12 int step[MAX];
13 queue<int>q;
14 void bfs()
15 {
16         while(!q.empty())
17         {
18               cur=q.front();
19               q.pop();
20               if(cur==k)  break;
21               next=cur-1;
22               if(next>=0&&step[next]==0)
23               {
24                       q.push(next);
25                       step[next]=step[cur]+1;
26               }
27               next=cur+1;
28               if(step[next]==0)
29               {
30                       q.push(next);
31                       step[next]=step[cur]+1;
32               }
33               next=cur*2;
34               if(next<=100000&&(next-k)<(k-cur)&&step[next]==0)
35               {
36                       q.push(next);
37                       step[next]=step[cur]+1;
38               }
39         }
40 
41 }
42 int main()
43 {
44        while(scanf("%d%d",&n,&k)!=EOF)
45        {
46               memset(step,0,sizeof(step));
47               if(n>k)
48                       cout<<(n-k)<<endl;
49                else
50                    {
51                         while(!q.empty()) q.pop();
52                         q.push(n);
53                         bfs();
54                         cout<<step[k]<<endl;
55                    }
56        }
57        return 0;
58 }
View Code

 

posted on 2013-08-09 16:04  GyyZyp  阅读(397)  评论(0编辑  收藏  举报

导航