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;
const int nx=505;
int n, w, h, dpa[nx][nx], dpb[nx][nx], dx[]={1, 0, -1, 0}, dy[]={0, 1, 0, -1}, ans=INT_MAX;
char mp[nx][nx];
pair<int, int> s1, s2;
int main()
{
cin.tie(NULL)->sync_with_stdio(false);
cin>>n>>w>>h;
for (int i=1; i<=h; i++)
{
for (int j=1; j<=w; j++)
{
cin>>mp[i][j];
if (mp[i][j]=='1') s1={i, j};
if (mp[i][j]=='2') s2={i, j};
}
}
queue<pair<int, int>> q;
for (int i=1; i<=h; i++) for (int j=1; j<=w; j++) dpa[i][j]=dpb[i][j]=INT_MAX;
dpa[s1.first][s1.second]=0;
q.push(s1);
while (!q.empty())
{
auto [x, y]=q.front();
q.pop();
for (int i=0; i<4; i++)
{
int tx=x, ty=y, d=i;
while (1)
{
if (mp[tx][ty]=='A') d=(d+1)%4;
if (mp[tx][ty]=='C') d=(d-1+4)%4;
tx=tx+dx[d];
ty=ty+dy[d];
if ((tx<1||tx>h||ty<1||ty>w)||mp[tx][ty]=='x')
{
tx=tx-dx[d];
ty=ty-dy[d];
if (dpa[tx][ty]>dpa[x][y]+1) dpa[tx][ty]=dpa[x][y]+1, q.push({tx, ty});
break;
}
}
}
}
dpb[s2.first][s2.second]=0;
q.push(s2);
while (!q.empty())
{
auto [x, y]=q.front();
q.pop();
for (int i=0; i<4; i++)
{
int tx=x, ty=y, d=i;
while (1)
{
if (mp[tx][ty]=='A') d=(d+1)%4;
if (mp[tx][ty]=='C') d=(d-1+4)%4;
tx=tx+dx[d];
ty=ty+dy[d];
if ((tx<1||tx>h||ty<1||ty>w)||mp[tx][ty]=='x')
{
tx=tx-dx[d];
ty=ty-dy[d];
if (dpb[tx][ty]>dpb[x][y]+1) dpb[tx][ty]=dpb[x][y]+1, q.push({tx, ty});
break;
}
}
}
}
for (int i=1; i<=h; i++) for (int j=1; j<=w; j++) if (dpa[i][j]!=INT_MAX&&dpb[i][j]!=INT_MAX) ans=min(ans, dpa[i][j]+dpb[i][j]);
cout<<((ans==INT_MAX)?-1:ans);
}
/*
2 3 3
1.x
.x.
x.2*/
# | 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... |