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 oo = INT_MAX;
int dx[] = {0,0,1,0,-1};
int dy[] = {0,1,0,-1,0};
int n,m,c[505][505];
priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>, greater<pair<int,pair<int,int>>>> h;
bool sel[505][505];
int d[505][505];
void Dijkstra(int x, int y)
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
d[i][j] = oo;
}
}
d[1][1] = 0;
if(c[x][y])
{
h.push({0,{x,y}});
}
int cnt = 0;
while(!h.empty())
{
while(!h.empty() && sel[h.top().second.first][h.top().second.second])
{
h.pop();
}
if(h.empty())
{
break;
}
int k = h.top().first;
int x = h.top().second.first;
int y = h.top().second.second;
h.pop();
sel[x][y] = true;
for(int p=1; p<=4; p++)
{
int xx = x + dx[p];
int yy = y + dy[p];
if(xx==1 && yy==1)
{
continue;
}
if(xx<1 || yy<1 || xx>n || yy>m)
{
continue;
}
int cost = 0;
if(p>=c[x][y])
{
cost = p-c[x][y];
}
else
{
cost = 4-c[x][y]+p;
}
if(xx==n && yy==m)
{
++cnt;
}
if(d[x][y]+cost<=d[xx][yy])
{
d[xx][yy] = d[x][y]+cost;
if(c[xx][yy])
{
h.push({d[xx][yy],{xx,yy}});
}
}
if(cnt==2)
{
return;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin>>n>>m;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
char ch;
cin>>ch;
if(ch=='E')
{
c[i][j] = 1;
}
else if(ch=='S')
{
c[i][j] = 2;
}
else if(ch=='W')
{
c[i][j] = 3;
}
else if(ch=='N')
{
c[i][j] = 4;
}
}
}
Dijkstra(1,1);
if(d[n][m]==oo)
{
cout<<-1<<'\n';
return 0;
}
cout<<d[n][m]<<'\n';
return 0;
}
Compilation message (stderr)
adventure.cpp: In function 'void Dijkstra(int, int)':
adventure.cpp:36:13: warning: unused variable 'k' [-Wunused-variable]
36 | int k = h.top().first;
| ^
# | 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... |