Cod sursa(job #2982325)

Utilizator TeoRoGaming_YgVoinea Ionut-Florin TeoRoGaming_Yg Data 19 februarie 2023 22:24:20
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.73 kb
#include <fstream>
#include <queue>

using namespace std;

const int N = 1000;
const int dl[] = {-1, 0, 1, 0};
const int dc[] = {0, -1, 0, 1};

int d[N+2][N+2], nl, nc;
pair <int, int> xi, xf;
bool accesibil[N+2][N+2];

bool ajung(int dist)
{
    if (d[xi.first][xi.second] < dist)
    {
        return false;
    }
    queue < pair <int, int>> q;
    for (int i = 1; i <= nl; i++)
    {
        for (int j = 1; j <= nc; j++)
        {
            accesibil[i][j] = true;
            if (d[i][j] < dist)
            {
                accesibil[i][j] = false;
            }
        }
    }
    q.push(xi);
    accesibil[xi.first][xi.second] = false;
    while (!q.empty())
    {
        pair <int, int> x = q.front();
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            pair <int, int> y = {x.first + dl[i], x.second + dc[i]};
            if (accesibil[y.first][y.second])
            {
                if (y == xf)
                {
                    return true;
                }
                accesibil[y.first][y.second] = false;
                q.push(y);
            }
        }
    }
    return false;
}

int main()
{
    ifstream f("barbar.in");
    ofstream g("barbar.out");
    queue < pair <int, int>> q;
    f >> nl >> nc;
    for (int i = 1; i <= nl; i++)
    {
        char lin[N+2];
        f >> (1 + lin);
        for (int j = 1; j <= nc; j++)
        {
            if (lin[j] == 'D')
            {
                q.push({i, j});
                d[i][j] = 0;
            }
            else if (lin[j] == '*')
            {
                d[i][j] = -2;
            }
            else
            {
                if (lin[j] == 'I')
                {
                    xi.first = i;
                    xi.second = j;
                }
                if (lin[j] == 'O')
                {
                    xf.first = i;
                    xf.second = j;
                }
                d[i][j] = -1;
            }
        }
    }
    f.close();
    while (!q.empty())
    {
        pair <int, int> x = q.front();
        q.pop();
        for (int i = 0; i < 4; i++)
        {
            pair <int, int> y = {x.first + dl[i], x.second + dc[i]};
            if (d[y.first][y.second] == -1)
            {
                d[y.first][y.second] = 1 + d[x.first][x.second];
                q.push(y);
            }
        }
    }
    int st = 0, dr = nl * nc, rez = -1;
    while (st <= dr)
    {
        int m = (st + dr) / 2;
        if (ajung(m))
        {
            rez = m;
            st = m + 1;
        }
        else
        {
            dr = m - 1;
        }
    }
    g << rez;
    g.close();
    return 0;
}