在一维数组上用类似BFS的思路做
再加上一些剪枝优化
优化:
1.跳到第n个格子提前结束
2.前面i+k[i]
已经覆盖过的范围可以不用再跳,因此需要记录已经覆盖过的i+k[i]
的最大值。
#include<iostream>
#include<queue>
using namespace std;
const int N=1e5+5;
int n;
int a[N],k[N],dis[N];
bool st[N];
void bfs(int s){
queue<int> q;
q.push(s);
st[s]=1;
int ma=2;
while(!q.empty()&&!dis[n]){
int t=q.front();q.pop();
for(int i=ma;i<=t+k[t];i++){
int e=i-a[i];
if(!st[e]){
q.push(e);
st[e]=1;
dis[e]=dis[t]+1;
}
}
ma=max(ma,t+k[t]);
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin >> n;
for(int i=1;i<=n;i++) cin >> a[i];
for(int i=1;i<=n;i++){
cin >> k[i];
k[i]=min(n-i,k[i]);
}
bfs(1);
if(dis[n]) cout << dis[n] << endl;
else cout << -1 << endl;
return 0;
}