Cod sursa(job #912250)

Utilizator apopeid13Apopeid Alejandro apopeid13 Data 12 martie 2013 10:49:19
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.5 kb
#include <fstream>
#include <queue>

using namespace std;

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

const int MAX_N = 1005;
const int INF = (1 << 30);
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, 1, 0, -1};

int n, m, pozl, pozc, iesireX, iesireY, D[MAX_N][MAX_N], rez[MAX_N][MAX_N];
char A[MAX_N][MAX_N];
queue < pair<int, int> > Q;

void read() {
    string s;
    f >> n >> m;
    for (int i = 1; i <= n; i++) {
        f >> s;
        for (int j = 0; j < m; j++) {
            A[i][j + 1] = s[j];
            if (s[j] == 'D') {
                Q.push (make_pair(i, j + 1));
                D[i][j + 1] = 0;
            } else if (s[j] == 'I') {
                pozl = i;
                pozc = j + 1;
            } else if (s[j] == 'O') {
                iesireX = i;
                iesireY = j + 1;
            }
        }
    }
}

void init() {
    for (int i = 1; i <= 1000; i++)
        for (int j = 1; j <= 1000; j++) {
            D[i][j] = INF;
            rez[i][j] = -1;
        }
}

int conditie(int l, int c) {
    if (l >= 1 && l <= n && c >= 1 && c <= m && A[l][c] != '*')
        return 1;
    return 0;
}

void lee() {
    while (!Q.empty()) {
        pair <int, int> X = Q.front();    Q.pop();
        for (int k = 0; k < 4; k++) {
            if (D[X.first][X.second] + 1 < D[X.first + dx[k]][X.second + dy[k]] && conditie(X.first + dx[k], X.second + dy[k])) {
                D[X.first + dx[k]][X.second + dy[k]] = D[X.first][X.second] + 1;
                Q.push (make_pair(X.first + dx[k], X.second + dy[k]));
            }
        }
    }
}

void lee_sukar() {
    rez[pozl][pozc] = D[pozl][pozc];

    Q.push (make_pair(pozl, pozc));
    while (!Q.empty()) {
        pair <int, int> X = Q.front();    Q.pop();
        for (int k = 0; k < 4; k++) {
            int l = X.first + dx[k];
            int c = X.second + dy[k];

            if (rez[l][c] == -1 && conditie(l, c)) {
                rez[l][c] = min(rez[X.first][X.second], D[l][c]);
                Q.push (make_pair(l, c));
            } else if (rez[X.first][X.second] > rez[l][c] && min(rez[X.first][X.second], D[l][c]) > rez[l][c] && conditie(l, c)) {
                rez[l][c] = min(rez[X.first][X.second], D[l][c]);
                Q.push (make_pair(l, c));
            }
        }
    }
}

int main() {
    init();
    read();
    lee();
    lee_sukar();

    g << rez[iesireX][iesireY] << '\n';

    f.close();
    g.close();

    return 0;
}