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

P1135 BFS例题

时间:2018-02-23 18:59:03      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:ios   pre   floor   print   头文件   col   处理   为什么   判断   

好,这是一道黄题。几个月前的我拿了可怜的20分。

这是当年的蒟蒻代码

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <cstdlib>
 6 using namespace std;
 7 
 8 int n,b,c;
 9 int a[201];
10 
11 int xiuxi(int now,int k)
12 {
13     if(k>200) return -1;
14     int aa=9999,bb=9999;
15     if(now == c) return k;
16 
17     if(now+a[now]<=n)
18     {
19         aa=xiuxi(now+a[now],k+1);
20     }
21     if(now-a[now]>0)
22     {
23         bb=xiuxi(now-a[now],k+1);
24     }
25     ///return ???;
26 }
27 
28 int main()
29 {
30     scanf ("%d%d%d",&n,&b,&c);
31     for(int i=1;i<=n;i++)
32     {
33         scanf ("%d",&a[i]);
34     }
35 
36     int ans=xiuxi(b,0);
37     printf("%d",ans);
38     return 0;
39 }

首先,头文件瞎加#(滑稽),然后,搜索的时候没有处理好无限循环,只能靠200那个上限来return,导致了TLE。xiuxi函数写的一塌糊涂。也没有确定是最小值就输出,导致了个WA。我也懒得改了。

今天重新看一看这个,就想到了预处理之后反着BFS。其实正着BFS也行。不知道我为什么脑子灵光一闪选择了反着。。

先交了一次,RE+WA 60分。先随手把几个数组开大到400,然后在BFS里解决了一个判断是否空队列,莫名A了。

这是AC代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 using namespace std;
 4 ///P1135
 5 int n,A,B,x;
 6 
 7 int p[402],ptop,ptail=1;
 8 bool vis[402];
 9 int step[402];
10 
11 struct floor{
12     int top,from[202];
13 }f[202];
14 
15 void bfs(int now)
16 {
17     for(int i=1;i<=f[now].top;i++)
18     {
19         if(vis[f[now].from[i]]) continue;
20         vis[f[now].from[i]]=1;
21         p[++ptop]=f[now].from[i];
22         step[f[now].from[i]]=step[now]+1;
23         if(f[now].from[i]==A) return;
24     }
25     if(ptop==ptail-1) return;
26     ptail++;
27     bfs(p[ptail-1]);
28     return;
29 }
30 
31 int main()
32 {
33     scanf ("%d%d%d",&n,&A,&B);
34     for(int i=1;i<=n;i++)
35     {
36         scanf ("%d",&x);
37         if(i-x>=1) f[i-x].from[++f[i-x].top]=i;
38         if(i+x<=n) f[i+x].from[++f[i+x].top]=i;
39     }
40     memset(step,-1,sizeof(step));
41 
42     vis[B]=true;
43     step[B]=0;
44     p[++ptop]=B;
45 
46     bfs(B);
47 
48     printf("%d",step[A]);
49     return 0;
50 }

手写队列,应该很好理解。可以拿来当BFS模板。这次去北京除了学了很多新知识以外,还意外的(意料之中的)提高了代码实现能力#(滑稽)。

那么就这样吧。晚安,11015.

P1135 BFS例题

标签:ios   pre   floor   print   头文件   col   处理   为什么   判断   

原文地址:https://www.cnblogs.com/huyufeifei/p/8462915.html

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