#include <bits/stdc++.h>
using namespace std;
const int mmod = 998244353;
#define vl vector<int>
#define vint vector<vector<int>>
int pow(int x, int n, int mod){
if (n == 0){
return 1;
}
int half = pow(x, n / 2, mod);
int half_square = (half * half) % mod;
if (n % 2 == 0) {
return half_square;
} else {
return (half_square * x) % mod;
}
}
int inversion_x(int x, int m){
int vysledek = pow(x,m-2);
return vysledek;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
int n;
int sx,sy;
int ex,ey;
cin >> n;
cin >> sy >> sx;
cin >> ey >> ex;
vl lines;
for (int i = 0; i<n; i++){
int num;
cin >> num;
lines.push_back(num);
}
queue<vl> fronta;
fronta.push({sx-1,sy-1,0});
set<pair<int,int>> visited;
if (sx == ex && sy == ey) {
cout << 0;
return 0;
}
vint dirs {{1,0},{-1,0},{0,1},{0,-1}};
while (fronta.size() > 0){
vl prvek = fronta.front();
fronta.pop();
int x = prvek[0];
int y = prvek[1];
int dist = prvek[2];
if (x == ex-1 && y == (ey-1)){
cout << dist;
break;
}
auto je = visited.find({x,y});
if (1 == 1){
int nx = x, ny = y;
if (x > 0) {
nx = x - 1;
} else if (x == 0 && y > 0) {
ny = y - 1;
nx = lines[ny];
} else {
nx = -1; // invalid
}
if (nx >= 0) {
if (visited.find({nx,ny}) == visited.end()) {
if (nx == ex-1 && ny == ey-1) {
cout << dist + 1;
return 0;
}
visited.insert({nx,ny});
fronta.push({nx, ny, dist + 1});
}
}
}
// Move right
{
int nx = x, ny = y;
if (x < lines[y]) {
nx = x + 1;
} else if (x == lines[y] && y < n - 1) {
ny = y + 1;
nx = 0;
} else {
nx = -1; // invalid
}
if (nx >= 0) {
if (visited.find({nx,ny}) == visited.end()) {
if (nx == ex-1 && ny == ey-1) {
cout << dist + 1;
return 0;
}
visited.insert({nx,ny});
fronta.push({nx, ny, dist + 1});
}
}
}
// Move up
if (y > 0) {
int ny = y - 1;
int nx = x > lines[ny] ? lines[ny] : x;
if (visited.find({nx,ny}) == visited.end()) {
if (nx == ex-1 && ny == ey-1) {
cout << dist + 1;
return 0;
}
visited.insert({nx,ny});
fronta.push({nx, ny, dist + 1});
}
}
// Move down
if (y < n - 1) {
int ny = y + 1;
int nx = x > lines[ny] ? lines[ny] : x;
if (visited.find({nx,ny}) == visited.end()) {
if (nx == ex-1 && ny == ey-1) {
cout << dist + 1;
return 0;
}
visited.insert({nx,ny});
fronta.push({nx, ny, dist + 1});
}
}
}
return 0;
}
# | 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... |