Cod sursa(job #2764450)

Utilizator DragosC1Dragos DragosC1 Data 20 iulie 2021 21:49:42
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.53 kb
#include <fstream>
#include <queue>
#include <iostream>
using namespace std;

int n, m;
int istart, jstart;
int istop, jstop;

bool a[1001][1001];

queue<pair<int, int>> Q;

int path[1001][1001];
const int Inf = 1e9;

void read() {
    int i, j;
    char ch;

    ifstream f("barbar.in");
    f >> n >> m;

    for (i = 1; i <= n; i++)
        for (j = 1; j <= m; j++)
            path[i][j] = Inf;

    for (i = 1; i <= n; i++)
        for (j = 1; j <= m; j++) {
            f >> ch;
            if (ch == 'I')
                istart = i, jstart = j;
            if (ch == 'O')
                istop = i, jstop = j;
            if (ch == '*')
                a[i][j] = 1;
            if (ch == 'D') {
                Q.push({i, j});
                path[i][j] = 0;
            }
        }
}

int rez;

const int di[] = {-1, 0, 1, 0};
const int dj[] = {0, 1, 0, -1};

bool inside(int i, int j) {
    if (i >= 1 && j >= 1 && i <= n && j <= m)
        return 1;
    return 0;
}

void lee1() {
    int i, j, inou, jnou, k;
    while (!Q.empty()) {
        i = Q.front().first, j = Q.front().second;
        for (k = 0; k < 4; k++) {
            inou = i + di[k], jnou = j + dj[k];
            if (inside(inou, jnou) && path[inou][jnou] > path[i][j] + 1 && !a[inou][jnou]) {
                Q.push({inou, jnou});
                path[inou][jnou] = path[i][j] + 1;
            } 
        }
        Q.pop();
    }
}

bool viz[1001][1001];

bool lee2(int x) {
    int i, j, inou, jnou, k;
    for (i = 1; i <= n; i++)
        for (j = 1; j <= m; j++)
            viz[i][j] = 0;
    viz[istart][jstart] = 1;
    Q.push({istart, jstart});
    while (!Q.empty()) {
        i = Q.front().first, j = Q.front().second;
        Q.pop();
        for (k = 0; k < 4; k++) {
            inou = i + di[k], jnou = j + dj[k];
            if (inside(inou, jnou) && !a[inou][jnou] && path[inou][jnou] >= x && !viz[inou][jnou]) {
                viz[inou][jnou] = 1;
                Q.push({inou, jnou});
            }
        }
    }
    return viz[istop][jstop];
}

void solve() {
    lee1();
    int i, j;
    int st = 0, dr = path[istart][jstart], mij;
    while (st <= dr) {
        mij = (st + dr) / 2;
        if (lee2(mij)) 
            st = mij + 1;
        else dr = mij - 1;
    }
    if (dr == 0)
        rez = -1;
    else rez = dr;
}

void output() {
    ofstream g("barbar.out");
    g << rez;
    g.close();
}

int main() {
    read();
    solve();
    output();
    return 0;
}