HDU 2717 简单的BFS

http://acm.hdu.edu.cn/showproblem.php?pid=2717

将每种状态加入到队列中,注意边界条件,n<0&&n>100000

注意N可以比K小,开始没注意,无限wa,还是太菜了啊。。。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<cmath>
 5 #include<algorithm>
 6 #include<queue>
 7 using namespace std;
 8 int c,b;
 9 int map[200010];
10 struct node
11 {
12     int step,ans;
13 };
14 int bfs()
15 {
16     queue<node>Q;
17     node q,next,p;
18     p.ans=c;
19     p.step=0;
20     memset(map,0,sizeof(map));
21     map[c]=1;
22     Q.push(p);
23     while(!Q.empty())
24     {
25         q=Q.front();
26         Q.pop();
27         if(q.ans==b)
28         return q.step;
29         for(int i=0;i<3;i++)
30         {
31             if(i==0)
32             next.ans=q.ans+1;
33             else if(i==1)
34             next.ans=q.ans-1;
35             else if(i==2)
36             next.ans=q.ans*2;
37             if(next.ans==b)
38             return q.step+1;
39             if(next.ans<0||map[next.ans]||next.ans>100000)
40             continue;
41             next.step=q.step+1;
42             map[next.ans]=1;
43             Q.push(next);
44         }
45     }
46     return -1;
47 }
48 int main()
49 {
50 
51     while(~scanf("%d%d",&c,&b))
52     printf("%d
",bfs());
53 }
原文地址:https://www.cnblogs.com/CrazyBaby/p/5709030.html