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

 

转载于:https://www.cnblogs.com/xiaozhuyang/p/hdu2717.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值