Cod sursa(job #2031774)

Utilizator CammieCamelia Lazar Cammie Data 3 octombrie 2017 19:39:40
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.66 kb
#include <fstream>
#include <queue>
#include <climits>

#define MAXN 1004

using namespace std;

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

struct elem{
    int lin,col;
};

queue <elem> Q;

elem Dir[4] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
int n, m, a[MAXN][MAXN], startx, starty, stopx, stopy;
int xx, yy, x, y, maxim;
int b[MAXN][MAXN];

inline void Read() {
    fin >> n >> m;

    char chr;

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            fin >> chr;

            if (chr == 'I') {
                startx = i; starty = j;
            }
            else if (chr == 'O') {
                stopx = i; stopy = j;
            }
            else if (chr == 'D') {
                a[i][j] = 1;
                Q.push({i, j});
            }
            else if (chr == '*')
                a[i][j] = -1;
        }
    }

    maxim = 1;
}

inline void Bordare() {
    for (int i = 0; i <= n + 1; i++) {
        a[i][0] = a[i][m + 1] = -1;
    }
    for (int i = 0; i <= m + 1; i++) {
        a[0][i] = a[n + 1][i] = -1;
    }
}

inline void Lee() {
    while (!Q.empty()) {
        xx = Q.front().lin;
        yy = Q.front().col;

        for (int k = 0; k < 4; k++) {
            x = xx + Dir[k].lin;
            y = yy + Dir[k].col;

            if (a[x][y] == 0) {
                a[x][y] = a[xx][yy] + 1;
                Q.push({x, y});

                if (a[x][y] > maxim)
                    maxim = a[x][y];
            }
        }

        Q.pop();
    }
}

inline int Test(int val) {
    Q = queue <elem> ();
   // memset(b, 0, sizeof(b));
    Q.push({startx, starty});
    if (a[startx][starty] < val)
        return 0;

    while (!Q.empty()) {
        xx = Q.front().lin;
        yy = Q.front().col;

        if (xx == stopx && yy == stopy)
            return 1;

        for (int k = 0; k < 4; k++) {
            x = xx + Dir[k].lin;
            y = yy + Dir[k].col;

            if (b[x][y] != val) {
                b[x][y] = val;
                if (a[x][y] >= val) {
                    Q.push({x, y});
                }
            }
        }
        Q.pop();
    }
    return 0;
}

inline void Solve() {

    int ls = 1, ld = maxim, mij, best = -1;

    while (ls <= ld) {
       mij = (ls + ld) / 2;

       if (Test(mij)) {
          best = mij;
          ls = mij + 1;
       }
       else
         ld = mij - 1;
    }

    if (best == -1)
        fout << best;
    else
        fout << best - 1;
}

int main () {
    Read();
    Bordare();
    Lee();
    Solve();

    fin.close(); fout.close(); return 0;
}