求助 30pts
查看原帖
求助 30pts
723738
KnowerHorse楼主2022/5/3 22:01

#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int arr[300];
int n,a,b;
bool vis[300];
queue<pair<int,int> > q;
bool ok(int shy){
    if(shy<0||shy>=n) return 0;
    else return 1;
}
void add(int now,int step){
    if(ok(now+arr[now])||vis[now+arr[now]]){q.push(make_pair(now+arr[now],step+1));vis[now+arr[now]]=1;}
    if(ok(now-arr[now])||vis[now-arr[now]]){q.push(make_pair(now-arr[now],step+1));vis[now-arr[now]]=1;}
    
    
}

int main(int argc, const char * argv[]) {
    cin>>n>>a>>b;
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    --a;--b;
    q.push(make_pair(a,0));
    pair<int,int> last={0,0};
    vis[a]=1;
    while(!q.empty()){
        last=q.front();
        q.pop();
        if(last.first==b)break;
        add(last.first,last.second);
    }
    if(last.first==b)cout<<last.second;
    else cout<<-1;
    cout<<endl;
    return 0;
}

QwQ bfs 30pts 4mle 1tle 2re

2022/5/3 22:01
加载中...