洛谷 P1135 奇怪的电梯 题解

题目链接

洛谷 P1135 奇怪的电梯

若 WA 58pts:题目中是从 \(A\) 开始,从 \(B\) 结束,而非从 \(1\)\(n\)

思路分析

中规中矩广搜题目。注意判断边界。

代码呈现

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;

const int N=205;
int n,a,b;
int k[N],mp[N];

void bfs(int st,int ed){
    queue<int> q;
    q.push(st),mp[st]=0;
    while (!q.empty()){
        int u=q.front();q.pop();
        if (u==ed) break;
        if (u+k[u]<=n && mp[u+k[u]]==-1) mp[u+k[u]]=mp[u]+1,q.push(u+k[u]);
        if (u-k[u]>=1 && mp[u-k[u]]==-1) mp[u-k[u]]=mp[u]+1,q.push(u-k[u]);
    }
}
int main(){
    scanf("%d%d%d",&n,&a,&b);
    for (int i=1;i<=n;++i) scanf("%d",k+i);
    memset(mp,-1,sizeof mp);
    bfs(a,b);
    printf("%d",mp[b]);
    return 0;
}
posted @ 2026-01-25 22:06  CodingJuRuo  阅读(2)  评论(0)    收藏  举报