Cod sursa(job #3378468)

Utilizator rapidu36Victor Manz rapidu36 Data 26 noiembrie 2026 16:01:19
Problema Barbar Scor 10
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.45 kb
#include <fstream>
#include <vector>
#include <string>
#include <queue>
#include <array>

using namespace std;

const int INF = 1e7;
const int ND = 4;
const int DL[ND] = {0, 1, 0, -1};
const int DC[ND] = {1, 0, -1, 0};

struct poz_mat {
    int l, c;
};

vector <vector <int>> d;

bool exista_drum(poz_mat x_ini, poz_mat x_fin, int dist, int nl, int nc) {
    if (d[x_ini.l][x_ini.c] < dist) {
        return false;
    }
    vector <vector <bool>> viz(nl + 1, vector<bool>(nc + 1, false));
    queue<poz_mat> q;
    viz[x_ini.l][x_ini.c] = true;
    q.push(x_ini);
    while (!q.empty()) {
        poz_mat x = q.front();
        q.pop();
        for (int i = 0; i < ND; i++) {
            poz_mat y = poz_mat(x.l + DL[i], x.c + DC[i]);
            if (d[y.l][y.c] >= dist && !viz[y.l][y.c]) {
                viz[y.l][y.c] = true;
                q.push(poz_mat(y.l, y.c));
            }
        }
    }
    return viz[x_fin.l][x_fin.c];
}

int main() {
    ifstream fin("barbar.in");
    ofstream fout("barbar.out");
    int nl, nc;
    fin >> nl >> nc;
    d.resize(nl + 2, vector<int>(nc + 2, -1));
    queue <poz_mat> q;
    poz_mat x_ini, x_fin;
    for (int i = 1; i <= nl; i++) {
        string linie;
        fin >> linie;
        for (int j = 1; j <= nc; j++) {
            d[i][j] = INF;
            if (linie[j-1] == 'D') {
                d[i][j] = 0;
                q.push(poz_mat(i, j));
                // q.push((poz_mat){i, j});
            } else if (linie[j-1] == 'I') {
                x_ini = poz_mat(i, j);
            } else if (linie[j-1] == 'O') {
                x_fin = poz_mat(i, j);
            } else if (linie[j-1] == '*') {
                d[i][j] = -1;
            }
        }
    }
    fin.close();
    while (!q.empty()) {
        poz_mat x = q.front();
        q.pop();
        for (int i = 0; i < ND; i++) {
            poz_mat y = poz_mat(x.l + DL[i], x.c + DC[i]);
            if (d[y.l][y.c] == INF) {
                d[y.l][y.c] = d[x.l][x.c] + 1;
                q.push(poz_mat(y.l, y.c));
            }
        }
    }

    for (auto linie: d) {
        for (auto element: linie) {
            fout << element << " ";
        }
        fout << "\n";
    }
    int st = 0, dr = nl * nc, rez = 0;
    while (st <= dr) {
        int m = (st + dr) / 2;
        if (exista_drum(x_ini, x_fin, m, nl, nc)) {
            rez = m;
            st = m + 1;
        } else {
            dr = m - 1;
        }
    }
    fout << rez << "\n";
    fout.close();
    return 0;
}