Cod sursa(job #2831966)

Utilizator PalcPalcu Stefan Palc Data 12 ianuarie 2022 16:12:37
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.36 kb
#include <bits/stdc++.h>
using namespace std;

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

char a[1003][1003];
int d[1003][1003], n, m;
int xi, yi, xo, yo;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
bitset<1003> viz[1003];
queue<pair<int, int>> q;

void Citire()
{
    int i;
    fin >> n >> m; fin.get();
    for (i = 1; i <= n; i++)
        fin.getline(a[i] + 1, 1003);
}

void Init()
{
    int i, j;
    for (i = 1; i <= n; i++)
        for (j = 1; j <= m; j++)
        {
            if (a[i][j] == 'D')
            {
                d[i][j] = 0;
                q.push({i, j});
            }
            else
            {
                d[i][j] = 1000005;
                if (a[i][j] == 'I')
                {
                    xi = i;
                    yi = j;
                }
                else if (a[i][j] == 'O')
                {
                    xo = i;
                    yo = j;
                }
            }
        }
}

void Bordare()
{
    int i, j;
    for (i = 0; i <= n + 1; i++)
        a[i][0] = a[i][m + 1] = '*';
    for (j = 0; j <= m + 1; j++)
        a[0][j] = a[n + 1][j] = '*';
}

void Lee()
{
    int i, j, x, y;
    while (!q.empty())
    {
        x = q.front().first;
        y = q.front().second;
        q.pop();
        for (int k = 0; k < 4; k++)
        {
            i = x + dx[k];
            j = y + dy[k];
            if (a[i][j] != '*' && d[i][j] > d[x][y] + 1)
            {
                d[i][j] = d[x][y] + 1;
                q.push({i, j});
            }
        }
    }
}

void Reset_Viz()
{
    int i;
    for (i = 1; i <= n; i++)
        viz[i].reset();
}

void Fill(int i, int j, int D)
{
    if (a[i][j] != '*' && d[i][j] >= D && viz[i][j] == 0)
    {
        viz[i][j] = 1;
        Fill(i - 1, j, D);
        Fill(i + 1, j, D);
        Fill(i, j - 1, D);
        Fill(i, j + 1, D);
    }
}

int CB()
{
    int st, dr, mij, dis;
    st = 1; dr = 1000000; dis = 0;
    while (st <= dr)
    {
        mij = (st + dr) / 2;
        Reset_Viz();
        Fill(xi, yi, mij);
        if (viz[xo][yo] == 1)
        {
            st = mij + 1;
            dis = mij;
        }
        else dr = mij - 1;
    }
    return dis;
}

int main()
{
    int ras;
    Citire();
    Init();
    Bordare();
    Lee();
    ras = CB();
    if (ras == 0) fout << "-1\n";
    else fout << ras << "\n";
    fin.close();
    fout.close();
    return 0;
}