Submission #1366852

#TimeUsernameProblemLanguageResultExecution timeMemory
1366852thanhbinh13Kraljica (COCI25_kraljica)C++20
110 / 110
2431 ms342900 KiB
#include<bits/stdc++.h>
#define pll pair<long long,pair<pair<long long,long long>,long long>>
using namespace std;

long long n,m;
char a[1005][1005];
vector<pair<long long,long long>> g[10];
long long dx[] = {0,0,1,1,1,-1,-1,-1};
long long dy[] = {1,-1,-1,0,1,-1,0,1};
long long distS[1005][1005][10];

void bfs(long long dist[1005][1005][10],pair<long long,long long> S) {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            for (int x = 0; x <= 8; x++) dist[i][j][x] = 1e18;
        }
    }
    priority_queue<pll,vector<pll>,greater<pll>> q;
    dist[S.first][S.second][8] = 0;
    q.push({0,{S,8}});
    while(!q.empty()) {
        long long u = q.top().second.first.first,v = q.top().second.first.second,dir = q.top().second.second;
        long long w = q.top().first;
        q.pop();
        if (dist[u][v][dir] != w) continue;
        for(int i = 0; i < 8; i++) {
            long long nu = u+dx[i],nv=  v+dy[i];
            if (nu > 0 && nu <= n && nv > 0 && nv <= m && a[nu][nv] != '#' && dist[nu][nv][i] > dist[u][v][dir]+(dir!= i)) {
                dist[nu][nv][i] = dist[u][v][dir]+(dir!= i);
                q.push({dist[nu][nv][i],{{nu,nv},i}});
            }
        }
        if (a[u][v] >= '0' && a[u][v] <= '9') {
            for (int i = 0; i < g[a[u][v]-'0'].size(); i++) {
                if (g[a[u][v]-'0'][i].first == u && g[a[u][v]-'0'][i].second == v) {
                    continue;
                }
                if (dist[g[a[u][v]-'0'][i].first][g[a[u][v]-'0'][i].second][8] > dist[u][v][dir]) {
                    dist[g[a[u][v]-'0'][i].first][g[a[u][v]-'0'][i].second][8] = dist[u][v][dir];
                    q.push({dist[g[a[u][v]-'0'][i].first][g[a[u][v]-'0'][i].second][8],{g[a[u][v]-'0'][i],8}});
                }
            }
        }
    }
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> m;
    pair<long long,long long>  S,E;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> a[i][j];
            if (a[i][j] == 'S') S = {i,j};
            if (a[i][j] == 'E') E = {i,j};
            if (a[i][j] >= '0' && a[i][j] <= '9') {
                g[a[i][j]-'0'].push_back({i,j});
            }
        }
    }
    bfs(distS,S);
    long long ans = 1e18;
    for (int i = 0; i <= 8; i++) ans = min(ans,distS[E.first][E.second][i]);
    if (ans == 1e18) ans = -1;
    cout << ans;
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...