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<cstdio>
#include<queue>
#include<memory.h>
#define origin 1061109567
#define MAX_N 1100
using namespace std;
struct data {
int x,y,v;
data() {
}
data(int x_,int y_,int v_) {
x = x_, y = y_, v = v_;
}
};
bool operator <(data X,data Y) {
return X.v > Y.v;
}
bool operator >(data X,data Y) {
return X.v < Y.v;
}
int n,m,ct,dir[5][2] = {{-1,0},{1,0},{0,1},{0,-1}};
char a[MAX_N][MAX_N];
int dist[MAX_N][MAX_N][4], sd[MAX_N][MAX_N], dp[MAX_N][MAX_N];
int x1,x2,y1,y2;
priority_queue<data> Q_;
inline void Push(int x,int y,int z) {
if(x>=0 && x<n && y>=0 && y<m && a[x][y]!='#' && dp[x][y]==origin) {
Q_.push(data(x,y,z));
}
}
int main()
{
memset(sd,-1,sizeof(sd));
memset(dp,0x3f,sizeof(dp));
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++) scanf("%s",a[i]);
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(a[i][j] == 'S') x1=i, y1=j;
if(a[i][j] == 'C') x2=i, y2=j;
}
}
for(int i=0;i<n;i++) dist[i][0][0] = (a[i][0]!='#' ? 1:0);
for(int i=0;i<n;i++) dist[i][m-1][1] = (a[i][m-1]!='#' ? 1:0);
for(int i=0;i<m;i++) dist[0][i][2] = (a[0][i]!='#' ? 1:0);
for(int i=0;i<m;i++) dist[n-1][i][3] = (a[n-1][i]!='#' ? 1:0);
for(int i=0;i<n;i++)
for(int j=1;j<m;j++) dist[i][j][0] = (a[i][j-1]!='#' ? dist[i][j-1][0]+1:1);
for(int i=0;i<n;i++)
for(int j=m-2;j>=0;j--) dist[i][j][1] = (a[i][j+1]!='#' ? dist[i][j+1][1]+1:1);
for(int i=0;i<m;i++)
for(int j=1;j<n;j++) dist[j][i][2] = (a[j-1][i]!='#' ? dist[j-1][i][2]+1:1);
for(int i=0;i<m;i++)
for(int j=n-1;j>=0;j--) dist[j][i][3] = (a[j+1][i]!='#' ? dist[j+1][i][3]+1:1);
Q_.push(data(x1,y1,1));
while(dp[x2][y2] == origin) {
data T = Q_.top();
Q_.pop();
if(dp[T.x][T.y]==origin) {
dp[T.x][T.y] = T.v;
for(int d=0;d<4;d++) Push(T.x+dir[d][0],T.y+dir[d][1],T.v+1);
int shortest = min(dist[T.x][T.y][2],dist[T.x][T.y][3]);
shortest = min(shortest,min(dist[T.x][T.y][0],dist[T.x][T.y][1]));
Push(T.x,T.y-dist[T.x][T.y][0]+1,T.v+shortest);
Push(T.x,T.y+dist[T.x][T.y][1]-1,T.v+shortest);
Push(T.x-dist[T.x][T.y][2]+1,T.y,T.v+shortest);
Push(T.x+dist[T.x][T.y][3]-1,T.y,T.v+shortest);
}
}
printf("%d\n\n",dp[x2][y2]-1);
/*
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) printf("%d ",dp[i][j]);
printf("\n");
}
printf("\n");
for(int d=0;d<3;d++) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) printf("%d ",dist[i][j][d]);
printf("\n");
}
printf("\n");
}
*/
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... |