洛谷 P1135 奇怪的电梯__(刷题)bfs

从今天开始,我要刷一些bfs或dfs 的题目了,现在开始的每道题都不简单(对于我而言)加油吧!

今天课上20mins刷了一道题,bfs,随便挑的。

课上只得到90分;

回到家,冷静一下,就通过打表得到了100分!!

是个好的开始!

题目戳这里

代码见下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1e6 + 5;
 4 
 5 int n,a,b;
 6 int x[maxn];
 7 int used[maxn];
 8 int k;
 9 bool is=false;
10 
11 struct node
12 {
13     int step,floor;
14 };
15 
16 void bfs()
17 {
18     queue<node> q;
19     q.push(node{0,a});
20     while(!q.empty())
21     {
22         node p=q.front();
23         q.pop();
24         if(p.floor == b)
25         {
26             printf("%d\n",p.step);
27             is=true;
28             return;
29         }
30         k = p.floor+x[p.floor];
31         if(k<=n && !used[k])
32         {
33             q.push(node{p.step+1,k});
34             used[k]=1;
35         }
36         k = p.floor-x[p.floor];
37         if(k>1 && !used[k])
38         {
39             q.push(node{p.step+1,k});
40             used[k]=1;
41         }
42     }
43 }
44 
45 int main()
46 {
47     scanf("%d%d%d",&n,&a,&b);
48     for(int i=1;i<=n;i++) scanf("%d",&x[i]);
49     if(b == a+x[a] || b == a-a[x])
50     {
51         printf("1\n");
52         return 0;
53     }
54     bfs();
55     if(!is) printf("-1\n");
56     return 0;
57 }

 

posted @ 2018-08-15 21:58  pengcheng_official  阅读(107)  评论(1编辑  收藏  举报