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>
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#define ti tuple<int, int, int>
using namespace std;
int r, c, dp[1010][1010], stx, sty, enx, eny, cx, cy, cdi, mn[1010][1010];
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
char arr[1010][1010];
pair<int, int> dir[4][1010][1010], cur;
priority_queue<ti, vector<ti>, greater<ti>> pq;
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> r >> c;
for(int i=0; i<1010; i++) for(int j=0; j<1010; j++) arr[i][j] = '#';
for(int i=1; i<=r; i++) {
for(int j=1; j<=c; j++) {
cin >> arr[i][j];
if(arr[i][j] == 'S') {
stx = i;
sty = j;
}
if(arr[i][j] == 'C') {
enx = i;
eny = j;
}
dp[i][j] = 1e9;
}
}
for(int j=0; j<=c+1; j++) {
for(int i=0; i<=r+1; i++) {
if(arr[i][j] == '#') cur = {i+1, j};
dir[0][i][j] = cur;
}
}
for(int i=0; i<=r+1; i++) {
for(int j=0; j<=c+1; j++) {
if(arr[i][j] == '#') cur = {i, j+1};
dir[1][i][j] = cur;
}
}
for(int j=0; j<=c+1; j++) {
for(int i=r+1; i>=0; i--) {
if(arr[i][j] == '#') cur = {i-1, j};
dir[2][i][j] = cur;
}
}
for(int i=0; i<=r+1; i++) {
for(int j=c+1; j>=0; j--) {
if(arr[i][j] == '#') cur = {i, j-1};
dir[3][i][j] = cur;
}
}
for(int i=1; i<=r; i++) {
for(int j=1; j<=c; j++) {
mn[i][j] = 1e9;
for(int k=0; k<4; k++) {
mn[i][j] = min(mn[i][j], abs(dir[k][i][j].first-i) + abs(dir[k][i][j].second-j));
}
}
}
pq.push({0, stx, sty});
while(pq.size()) {
cdi = get<0>(pq.top());
cx = get<1>(pq.top());
cy = get<2>(pq.top());
pq.pop();
if(cx < 1 || cx > r || cy < 1 || cy > c || dp[cx][cy] <= cdi || arr[cx][cy] == '#') continue;
dp[cx][cy] = cdi;
if(cx == enx && cy == eny) {
cout << dp[enx][eny];
return 0;
}
for(int i=0; i<4; i++) {
pq.push({cdi+1, cx+dx[i], cy+dy[i]});
}
for(int i=0; i<4; i++) {
pq.push({cdi+mn[cx][cy]+1, dir[i][cx][cy].first, dir[i][cx][cy].second});
}
}
cout << dp[enx][eny];
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... |