bfs写的58分 换成dijkstra就过了
//58分bfs
#include<bits/stdc++.h>
using namespace std;
int n,a,b,k[205];
struct node{
int f,s;
};
bool vis[205];
void bfs(int st,int t) {
queue<node> q;
q.push({st,0});
vis[st] = true;
while(!q.empty()) {
node x = q.front();
q.pop();
int floor = x.f;
int step = x.s;
if(floor == t) {
cout << step;
return;
}
int up = floor + k[floor];
int down = floor - k[floor];
if(!vis[up] && up <= t) {
q.push({up,step+1});
vis[up] = true;
}else {
if(!vis[down] && down >= 1) {
q.push({down,step+1});
vis[down] = true;
}else {
cout << -1;
return;
}
}
}
}
int main() {
cin >> n >> a >> b;
for(int i = 1;i<=n;i++) {
cin >> k[i];
}
bfs(a,b);
return 0;
}
//满分dijkstra
#include<bits/stdc++.h>
using namespace std;
const int N = 250;
int n,s,k,dis[N];
vector<pair<int,int> > e[N];
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > q;
bool vis[N];
void dijkstra(int s) {
q.push({0,s});
dis[s] = 0;
while(!q.empty()) {
int d = q.top().first;
int u = q.top().second;
q.pop();
if(vis[u]) continue;
vis[u] = 1;
for(auto it : e[u]) {
int v = it.first;
int w = it.second;
if(dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
q.push({dis[v],v});
}
}
}
}
int main() {
cin >> n >> s >> k;
for(int i = 1;i<=n;i++) {
int x;
cin >> x;
if(i + x <= n) {
e[i].push_back({i + x,1});
}
if(i - x >= 1) {
e[i].push_back({i - x,1});
}
dis[i] = 1e9;
}
dijkstra(s);
if(dis[k] == 1e9) {
cout << -1;
}else {
cout << dis[k];
}
return 0;
}
bfs求调