Cod sursa(job #2848938)

Utilizator Ion.AAlexandru Ion Ion.A Data 14 februarie 2022 11:30:40
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.68 kb
#include <fstream>
#include <queue>
#include <cstring>

using namespace std;

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

const int NMAX = 1e3 + 1;
char ma[NMAX][NMAX];
bool viz[NMAX][NMAX], a[NMAX][NMAX];
int rez[NMAX][NMAX];
int n, m;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};

struct point{
    int x, y;
};

point aux, nou, st, bar, fn;
queue <point> q;

bool valid(int lung)
{
    memset(viz, 0, sizeof(viz));
    q.push(bar);
    while (!q.empty())
    {
        aux = q.front();
        for (int i = 0; i < 4; i++)
        {
            nou.x = aux.x + dx[i];
            nou.y = aux.y + dy[i];
            if ((nou.x >= 0 && nou.x < n) && (nou.y >= 0 && nou.y < m))
            {
                if (!a[nou.x][nou.y] && !viz[nou.x][nou.y] && rez[nou.x][nou.y] >= lung)
                {
                    viz[nou.x][nou.y] = 1;
                    q.push(nou);
                }
            }
        }
        q.pop();
    }
    return viz[fn.x][fn.y];
}

int caut_bin()
{
    int sta = 0, dr = n + m, mij, last = -1;
    while (sta <= dr)
    {
        mij = (sta + dr) / 2;
        if (valid(mij))
        {
            sta = mij + 1;
            last = mij;
        }
        else
        {
            dr = mij - 1;
        }
    }
    return last;
}

int main()
{
    in >> n >> m;
    in.getline(ma[0], m + 1);
    for (int i = 0; i < n; i++)
    {
        in.getline(ma[i], m + 1);
    }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (ma[i][j] == '*')
            {
                a[i][j] = 1;
            }
            else if (ma[i][j] == 'D')
            {
                st.x = i;
                st.y = j;
                viz[st.x][st.y] = 1;
                q.push(st);
            }
            else if (ma[i][j] == 'I')
            {
                bar.x = i;
                bar.y = j;
            }
            else if (ma[i][j] == 'O')
            {
                fn.x = i;
                fn.y = j;
            }
        }
    }
    while (!q.empty())
    {
        aux = q.front();
        for (int i = 0; i < 4; i++)
        {
            nou.x = aux.x + dx[i];
            nou.y = aux.y + dy[i];
            if ((nou.x >= 0 && nou.x < n) && (nou.y >= 0 && nou.y < m))
            {
                if (!a[nou.x][nou.y] && !viz[nou.x][nou.y])
                {
                    viz[nou.x][nou.y] = 1;
                    rez[nou.x][nou.y] = rez[aux.x][aux.y] + 1;
                    q.push(nou);
                }
            }
        }
        q.pop();
    }
    out << caut_bin();
    return 0;
}