Cod sursa(job #2781598)

Utilizator MateiAruxandeiMateiStefan MateiAruxandei Data 9 octombrie 2021 22:05:35
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.27 kb
#include <bits/stdc++.h>

#define NMAX 1005
using namespace std;

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

const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};

int stX, stY, fsX, fsY, dis[NMAX][NMAX], rasp[NMAX][NMAX];

queue<pair<int, int> > q1, q2;

void leeDragoni(){
    while(!q1.empty()){
        auto p = q1.front();
        q1.pop();
        for(int k = 0; k < 4; ++k){
            int newX = p.first + dx[k];
            int newY = p.second + dy[k];

            if(dis[newX][newY] == 0){
                dis[newX][newY] = dis[p.first][p.second] + 1;
                q1.push({newX, newY});
            }
        }
    }
}

inline bool test(int val){
    if(dis[stX][stY] < val)
        return 0;

    q2.push({stX, stY});
    while(!q2.empty()){
        auto p = q2.front();
        q2.pop();

        for(int k = 0; k < 4; ++k){
            int newX = p.first + dx[k];
            int newY = p.second + dy[k];

            if(rasp[newX][newY] != -1 && rasp[newX][newY] != val && dis[newX][newY] >= val){
                rasp[newX][newY] = val;
                q2.push({newX, newY});
            }
        }
    }
    return (rasp[fsX][fsY] == val);
}

int main()
{
    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= n; ++i)
        dis[i][0] = dis[i][m + 1] = rasp[i][0] = rasp[i][m + 1] = -1;
    for(int j = 1; j <= m; ++j)
        dis[0][j] = dis[n + 1][j] = rasp[0][j] = rasp[n + 1][j] = -1;

    fin.get();
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j)
        {
            char c;
            fin >> c;

            if(c == '*')
                dis[i][j] = -1, rasp[i][j] = -1;
            if(c == 'D'){
                q1.push({i, j});
                dis[i][j] = 1;
            }
            if(c == 'I')
                stX = i, stY = j;
            if(c == 'O')
                fsX = i, fsY = j;
        }

    leeDragoni();

    int st = 1;
    int best = -1;
    int dr = n * m;
    while(st <= dr){
        int mij = (st + dr) / 2;
        if(test(mij)){
            best = mij;
            st = mij + 1;
        }
        else dr = mij - 1;
    }

    if(best == -1)
        fout << -1 << '\n';
    else fout << best - 1 << '\n';
    return 0;
}