This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// Solid <candgenesis>
#include <bits/stdc++.h>
#define ll int
#define ld long double
#define fs first
#define sc second
using namespace std;
const ll N = 1e3 + 12;
const ll inf = 1e9 + 7;
typedef pair<ll,ll> LL;
char a[N][N];
ll n,m,i,j,d[N][N];
LL dp[N][N][4],start,en,direct[4];
vector<LL> g[N][N];
bool chk(ll x,ll y){
return (x >= 1&&y >= 1&&x <= n&&y <= m);
}
ll dx[4] = {0,0,1,-1};
ll dy[4] = {1,-1,0,0};
LL DFS(ll x,ll y,ll cond){
ll p = x + dx[cond],q = y + dy[cond];
if (a[p][q] == '#') return {x,y};
if (dp[p][q][cond].fs != 0) return dp[p][q][cond];
return dp[p][q][cond] = DFS(p,q,cond);
}
struct Node{
ll val,x,y;
};
bool operator < (Node x,Node y){
return (x.val < y.val)||(x.val == y.val&&x.x < y.x)||(x.val == y.val&&x.x == y.x&&x.y < y.y);
}
void Dij(ll x,ll y){
set<Node> s; d[x][y] = 0;
s.insert({d[x][y],x,y});
while(!s.empty()){
Node t = *s.begin(); s.erase(s.begin());
ll val = t.val;
for (auto i : g[t.x][t.y]){
ll u = i.fs,v = i.sc;
if (a[u][v] == '#') continue;
if (d[u][v] > val + 1){
s.erase({d[u][v],u,v});
d[u][v] = val + 1;
s.insert({d[u][v],u,v});
}
}
ll minn = inf;
for (ll i = 0;i < 4;i++){
direct[i] = DFS(t.x,t.y,i);
minn = min(minn,abs(direct[i].fs - t.x) + abs(direct[i].sc - t.y));
}
for (ll i = 0;i < 4;i++){
ll u = direct[i].fs,v = direct[i].sc;
if (d[u][v] > val + 1 + minn){
s.erase({d[u][v],u,v});
d[u][v] = val + 1 + minn;
s.insert({d[u][v],u,v});
}
}
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
#define task "tst"
if (fopen(task".inp", "r")){
freopen(task".inp", "r", stdin);
//freopen(task".out", "w", stdout);
}
cin>>n>>m;
for (i = 0;i <= n + 1;i++){
for (j = 0;j <= m + 1;j++){
if (!i||!j||j > m||i > n) a[i][j] = '#';
else{
cin>>a[i][j]; d[i][j] = inf;
if (a[i][j] == 'S') start = {i,j};
if (a[i][j] == 'C') en = {i,j};
for (ll k = 0;k < 4;k++){
ll p = i + dx[k],q = j + dy[k];
if (chk(p,q)) g[i][j].push_back({p,q});
}
}
}
}
Dij(start.fs,start.sc);
cout<<d[en.fs][en.sc];
}
Compilation message (stderr)
portals.cpp: In function 'int main()':
portals.cpp:67:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)', declared with attribute warn_unused_result [-Wunused-result]
67 | freopen(task".inp", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
# | 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... |