hdu 1548 A strange lift

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

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <queue>
 4 #include <cstring>
 5 #include <algorithm>
 6 #define maxn 300
 7 using namespace std;
 8 
 9 int g[maxn][maxn];
10 int n;
11 int A,B;
12 bool vis[maxn];
13 int step[maxn];
14 int a[maxn];
15 bool flag=true;
16 
17 void bfs(int src)
18 {
19     memset(vis,false,sizeof(vis));
20     queue<int>q;
21     q.push(src);
22     step[src]=0;
23     vis[src]=true;
24     while(!q.empty())
25     {
26         int u=q.front(); q.pop();
27         if(u==B)
28         {
29             flag=false;
30             return ;
31         }
32         int next=u+a[u];
33         if(next>=1&&next<=n&&!vis[next])
34         {
35             step[next]=step[u]+1;
36             vis[next]=true;
37             q.push(next);
38         }
39         next=u-a[u];
40         if(next>=1&&next<=n&&!vis[next])
41         {
42             step[next]=step[u]+1;
43             vis[next]=true;
44             q.push(next);
45         }
46     }
47 }
48 int main()
49 {
50     while(scanf("%d",&n)!=EOF)
51     {
52         if(n==0) break;
53         scanf("%d%d",&A,&B);
54         for(int i=1; i<=n; i++)
55         {
56             cin>>a[i];
57         }
58         flag=true;
59         bfs(A);
60         if(!flag)
61         printf("%d
",step[B]);
62         else
63         printf("-1
");
64     }
65     return 0;
66 }
View Code
原文地址:https://www.cnblogs.com/fanminghui/p/3691887.html