#include <bits/stdc++.h>
using namespace std;
int n,p,l,r;
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n>>p>>l>>r;
vector<int> map(n,-1);
map[0]=0;
vector<int> s(n);
for(int i=0;i<n;i++){
cin>>s[i];
}
queue<pair<int,int>>q;
q.push(make_pair(0,0));
while(!q.empty()){
int now=q.front().first;
int t=q.front().second;
q.pop();
if(now==p){
break;
}
if(now+r<n&&map[s[now+r]]==-1){
q.push(make_pair(s[now+r],t+1));
map[s[now+r]]=t+1;
}
if(now-l>0&&map[s[now-l]]==-1){
q.push(make_pair(s[now-l],t+1));
map[s[now-l]]=t+1;
}
}
cout<<map[p];
}
題目中有說 n<=10^6, 而 |s|<=10^8
樓上所附程式中,好像並未檢查map[]中的索引是否超出範圍
應該是測資未表現出|s|<=10^8的精神吧,不然應會出問題?vector map(n,-1);
map[0]=0;
vector s(n);
...
if(now+r
q.push(make_pair(s[now+r],t+1));
map[s[now+r]]=t+1;
}
if(now-l>0&&map[s[now-l]]==-1){
q.push(make_pair(s[now-l],t+1));
map[s[now-l]]=t+1;
}我用這個測資,測試執行時發生 【記憶體區段錯誤!Segmentation fault (core dumped】
10 3 5 7
0 1234567 2 3 4 9999999 5 6 7 -88