Nu aveti permisiuni pentru a descarca fisierul grader_test8.in

Cod sursa(job #2709494)

Utilizator JackstilAdascalitei Alexandru Jackstil Data 20 februarie 2021 12:41:23
Problema Barbar Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.68 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <algorithm>
#include <vector>
#define NMAX 1001

using namespace std;

ifstream in("barbar.in");
ofstream out("barbar.out");

int n, m, ans;
char mat[NMAX][NMAX];
int dp[NMAX][NMAX];
bool inn[NMAX][NMAX], afisat;
pair<int, int> x, y, dragon;

struct cmp {
    bool operator()(pair<int, int> a, pair<int, int> b) {
        return dp[a.first][a.second] < dp[b.first][b.second];
    }
};

int coord[4] = {0, 1, 0, -1}, coord2[4] = {1, 0, -1, 0};
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> q;

void findRoad(int i, int j) {
    q.push({i, j});
    while (!q.empty()) {
        i = q.top().first;
        j = q.top().second;
        q.pop();

        if (i == y.first && j == y.second) {
            out << dp[i][j];
            afisat = true;
            return;
        }

        for (int d = 0; d < 4; ++d) {
            int toL = i + coord[d], toC = j + coord2[d];
            if (mat[toL][toC] == '.') {
                dp[toL][toC] = min(dp[toL][toC], dp[i][j]);
                if (!inn[toL][toC]) {
                    q.push({toL, toC});
                    inn[toL][toC] = true;
                }
            }
        }
    }
}

int main() {
    in >> n >> m;
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= m; ++j) {
            in >> mat[i][j];

            if (mat[i][j] == 'D')
                dragon = {i, j};
            else if (mat[i][j] == 'I') {
                x = {i, j};
                mat[i][j] = '.';
            } else if (mat[i][j] == 'O') {
                y = {i, j};
                mat[i][j] = '.';
            }
            dp[i][j] = INT_MAX;
        }

    queue<pair<int, int> > q2;
    q2.push({dragon.first, dragon.second});
    dp[dragon.first][dragon.second] = 0;
    while (!q2.empty()) {
        int i = q2.front().first;
        int j = q2.front().second;
        q2.pop();
        inn[i][j] = false;
        for (int d = 0; d < 4; ++d) {
            int toL = i + coord[d], toC = j + coord2[d];

            if (mat[toL][toC] == 'D' && dp[toL][toC] != 0) {
                dp[toL][toC] = 0;
                if (!inn[toL][toC]) {
                    q2.push({toL, toC});
                    inn[toL][toC] = true;
                }
            } else if (dp[i][j] + 1 < dp[toL][toC] && mat[toL][toC] == '.') {
                dp[toL][toC] = dp[i][j] + 1;
                if (!inn[toL][toC]) {
                    q2.push({toL, toC});
                    inn[toL][toC] = true;
                }
            }
        }
    }

    findRoad(x.first, x.second);
    if (!afisat)
        out << -1;
    return 0;
}