This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
int calc(int x1, int y1, int x2, int y2){
return abs(x2 - x1) + abs (y2 - y1);
}
int main(){
int n;
cin >> n;
int x1,y1,x2,y2;
cin >> x1 >> y1 >> x2 >> y2;
int arr[n + 1];
int t1 = 0;
for(int i = 1; i <= n; i++){
cin >> arr[i];
if(arr[i] > 5000){
t1++;
}
}
arr[0] = arr[1];
if(t1 > 0 or n > 5000){
if(n == 1){
cout << 0 <<endl;
}else{
int res1 = calc(x1,y1,x2,y2);
int res2 = 1e9;
if(x1 != n){
res2 = (arr[0] + 2) - y1 + calc(x1 + 1, 1, x2, y2);
}
int res3 = 1e9;
if(x1 != 1){
res3 = y1 + calc(x1 - 1, arr[0] + 1, x2, y2);
}else{
res3 = 1 + y1 + calc(1, arr[0] + 1, x2, y2);
}
int res4 = n - x1;
res4 = res4 + 1 + min(calc(n - 1, 1, x2, y2), calc(n - 1, arr[0] + 1, x2, y2));
res1 = min(res1, res2);
res1 = min(res1, res3);
res1 = min(res1, res4);
cout << res1;
}
}else{
long long int dp[n + 2][5002];
long long int vis[n + 2][5002];
for(int i = 1; i <= n; i++){
for(int j = 1; j <= 5000; j++){
dp[i][j] = 1e9;
vis[i][j] = 0;
}
}
queue<pair<int,int>>q;
q.push({x1,y1});
dp[x1][y1] = 0;
vis[x1][y1]++;
while(!q.empty()){
pair<int,int>v = q.front();
q.pop();
int x = v.first;
int y = v.second;
if(x == x2 and y == y2){
cout << dp[x][y];
return 0;
}
int nx,ny;
if(y != (arr[x] + 1)){
nx = x;
ny = y + 1;
if(vis[nx][ny] == 0){
dp[nx][ny] = dp[x][y] +1;
q.push({nx,ny});
vis[nx][ny]++;
}
}else{
if(x != n){
nx = x + 1;
ny = 1;
if(vis[nx][ny] == 0){
dp[nx][ny] = dp[x][y] +1;
q.push({nx,ny});
vis[nx][ny]++;
}
}
}
if(y > 1){
nx = x;
ny = y - 1;
if(vis[nx][ny] == 0){
dp[nx][ny] = dp[x][y] +1;
q.push({nx,ny});
vis[nx][ny]++;
}
}else{
if(x != 1){
nx = x - 1;
ny = arr[x - 1] + 1;
if(vis[nx][ny] == 0){
dp[nx][ny] = dp[x][y] +1;
q.push({nx,ny});
vis[nx][ny]++;
}
}
}
if(x != 1){
nx = x - 1;
ny = min(arr[x - 1] + 1, y);
if(vis[nx][ny] == 0){
dp[nx][ny] = dp[x][y] +1;
q.push({nx,ny});
vis[nx][ny]++;
}
}
if(x != n){
nx = x + 1;
ny = min(arr[x + 1] + 1, y);
if(vis[nx][ny] == 0){
dp[nx][ny] = dp[x][y] +1;
q.push({nx,ny});
vis[nx][ny]++;
}
}
}
// cout << endl;
// cout << dp[2][1] << endl;
}
}
# | 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... |