#include <bits/stdc++.h>
#define int long long
#define pb push_back
#define ff first
#define ss second
#define all(x) x.begin(),x.end()
using namespace std;
vector <int> dis[1005];
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int n;
cin>>n;
int a,b,c,d;
cin>>a>>b>>c>>d;
vector <int> l(n);
for(int i=0;i<n;i++){
cin>>l[i];
if(n>=3){
dis[i+1].pb(-1);
for(int j=0;j<l[i]+1;j++){
dis[i+1].pb(-1);
}
}
}
if(n==1){
cout<<abs(b-d)<<"\n";
return 0;
}
if(n==2){
if(a==c){
cout<<abs(b-d)<<"\n";
}
else{
int ans=abs(b-d)+1;
if(a==1){
ans=min(ans,(l[0]+1-b)+min(d,1+ (l[1]+1-d)));
}
else{
ans=min(ans,d-1+min(l[0]+1-b+1,b));
}
cout<<ans<<"\n";
}
return 0;
}
dis[a][b]=0;
queue <pair <int,int> > q;
q.push({a,b});
while(!q.empty()){
int x=q.front().ff;
int y=q.front().ss;
q.pop();
if(y-1>=1){
if(dis[x][y-1]==-1){
dis[x][y-1]=dis[x][y]+1;
q.push({x,y-1});
}
}
else if(x-1>=1){
if(dis[x-1][l[x-2]+1]==-1){
dis[x-1][l[x-2]+1]=dis[x][y]+1;
q.push({x-1,l[x-2]+1});
}
}
if(y+1<=l[x-1]+1){
if(dis[x][y+1]==-1){
dis[x][y+1]=dis[x][y]+1;
q.push({x,y+1});
}
}
else if(x+1<=n){
if(dis[x+1][1]==-1){
dis[x+1][1]=dis[x][y]+1;
q.push({x+1,1});
}
}
if(x-1>=1){
if(dis[x-1][min(y,l[x-2]+1)]==-1){
dis[x-1][min(y,l[x-2]+1)]=dis[x][y]+1;
q.push({x-1,min(y,l[x-2]+1)});
}
}
if(x+1<=n){
if(dis[x+1][min(y,l[x]+1)]==-1){
dis[x+1][min(y,l[x]+1)]=dis[x][y]+1;
q.push({x+1,min(y,l[x]+1)});
}
}
}
cout<<dis[c][d]<<"\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |