1360奇怪的电梯

题目链接:http://ybt.ssoier.cn:8088/problem_show.php?pid=1360

方法一:BFS

 1 #include <cstdio>
 2 #include <queue>
 3 using namespace std;
 4 int n,m,a,b;
 5 int q[250],vis[250];
 6 int main()
 7 {
 8     int i;
 9     queue<int>p;
10     scanf("%d%d%d",&n,&a,&b);
11     vis[a]=1;
12     for(i=1;i<=n;i++)scanf("%d",&q[i]);
13     p.push(a);
14     while(!p.empty())
15     {
16         int now=p.front(),l=now-q[now],r=now+q[now];
17         if(l>=1&&!vis[l]){//电梯向下 
18             p.push(l);
19             vis[l]=vis[now]+1;
20         }
21         if(r<=n&&!vis[r]){//电梯向上
22             p.push(r);
23             vis[r]=vis[now]+1;
24         }
25         if(l==b||r==b)break;//到达目标b 
26         p.pop();
27     }
28     printf("%d\n",vis[b]-1);
29     return 0;
30 }

其实这是个最短路问题,于是还可以用以下两种算法

方法二:floyd算法

方法三:dijkstra算法

猜你喜欢

转载自www.cnblogs.com/tflsnoi/p/10172983.html
今日推荐