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;
#define int long long
#define pb push_back
#define sz(a) (int)a.size()
const int mxN = (int)1e3+10;
using ar = array<int,3>;
int X[] = {1,-1,0,0};
int Y[] = {0,0,1,-1};
string a[mxN];
bool vis[mxN][mxN];
int n, m, stX, stY, enX, enY;
pair<int,int> dir[4][mxN][mxN];
int dis[mxN][mxN], sh[mxN][mxN];
priority_queue<ar,vector<ar>,greater<ar>> pq;
bool valid(int i, int j){
return i>=0 and j>=0 and i<n and j<m and a[i][j]!='#';
}
void bfs(int sti, int stj){
memset(dis,63,sizeof(dis));
pq.push({0,sti,stj}); dis[sti][stj] = 0;
while(!pq.empty()){
auto [w,i,j] = pq.top(); pq.pop();
if(vis[i][j]) continue; vis[i][j]=1;
for(int k = 0; k < 4; k++){
int ni = i+X[k], nj = j+Y[k];
if(valid(ni,nj) and dis[ni][nj]>dis[i][j]+1)
dis[ni][nj] = dis[i][j]+1, pq.push({dis[ni][nj],ni,nj});
}
for(int k = 0; k < 4; k++){
auto [ni,nj] = dir[k][i][j];
if(valid(ni,nj) and dis[ni][nj]>dis[i][j]+sh[i][j])
dis[ni][nj] = dis[i][j]+sh[i][j], pq.push({dis[ni][nj],ni,nj});
}
}
}
int32_t main(){
cin >> n >> m; memset(sh,63,sizeof(sh));
for(int i = 0; i < n; i++){
cin >> a[i];
for(int j = 0; j < m; j++){
if(a[i][j]=='C') enX=i,enY=j;
else if(a[i][j]=='S') stX=i,stY=j;
}
}
for(int i = 0; i < n; i++){
int last = 0;
for(int j = 0; j < m; j++){
if(a[i][j]=='#') last = j+1;
else dir[0][i][j]={i,last},sh[i][j]=min(sh[i][j],abs(last-j)+1);
}
last = m-1;
for(int j = m-1; j >= 0; j--){
if(a[i][j]=='#') last = j-1;
else dir[1][i][j]={i,last},sh[i][j]=min(sh[i][j],abs(last-j)+1);
}
}
for(int j = 0; j < m; j++){
int last = 0;
for(int i = 0; i < n; i++){
if(a[i][j]=='#') last = i+1;
else dir[2][i][j]={last,j},sh[i][j]=min(sh[i][j],abs(last-i)+1);
}
last = n-1;
for(int i = n-1; i >= 0; i--){
if(a[i][j]=='#') last = i-1;
else dir[3][i][j]={last,j},sh[i][j]=min(sh[i][j],abs(last-i)+1);
}
}
bfs(stX,stY); cout << dis[enX][enY];
}
Compilation message (stderr)
portals.cpp: In function 'void bfs(long long int, long long int)':
portals.cpp:27:3: warning: this 'if' clause does not guard... [-Wmisleading-indentation]
27 | if(vis[i][j]) continue; vis[i][j]=1;
| ^~
portals.cpp:27:27: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'if'
27 | if(vis[i][j]) continue; vis[i][j]=1;
| ^~~
# | 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... |