Cod sursa(job #2673029)

Utilizator StanCatalinStanCatalin StanCatalin Data 15 noiembrie 2020 17:36:59
Problema Barbar Scor 10
Compilator cpp-64 Status done
Runda ursus_retro_fara_alcool Marime 2.72 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <cstring>

using namespace std;

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

const int dim = 1005;
const int INF = dim*dim + dim;
const int di[] = {-1,0,1,0};
const int dj[] = {0, 1,0,-1};

int n,m,a[dim][dim],d[dim][dim],viz[dim][dim];

queue<pair<int,int> > q;
pair<int,int> start;
pair<int,int> unde;
string s;

bool Inauntru(int x,int y)
{
    return (x >= 1 && x <= n && y >= 1 && y <= m);
}

void BFS()
{
    while (!q.empty())
    {
        pair<int,int> x = q.front();
        q.pop();
        for (int k=0; k<4; k++)
        {
            pair<int,int> y = {x.first + di[k], x.second + dj[k]};
            if (Inauntru(y.first, y.second) && a[y.first][y.second] == 0 && d[y.first][y.second] > 1 + d[x.first][x.second])
            {
                d[y.first][y.second] = 1 + d[x.first][x.second];
                q.push(y);
            }
        }
    }
}

bool Check(int val)
{
    memset(viz,0, sizeof(viz));
    q.push(start);
    viz[start.first][start.second] = 1;
    while (!q.empty())
    {
        pair<int,int> x = q.front();
        q.pop();
        for (int k=0; k<4; k++)
        {
            pair<int,int> y = {x.first + di[k], x.second + dj[k]};
            if (Inauntru(y.first, y.second) && a[y.first][y.second] == 0 && !viz[y.first][y.second] && d[y.first][y.second] >= val)
            {
                viz[y.first][y.second] = 1;
                q.push(y);
            }
        }
    }

    return viz[unde.first][unde.second];
}

int main()
{
    in >> n >> m;
    for (int i=1; i<=n; i++)
    {
        for (int j=1; j<=m; j++)
        {
            d[i][j] = INF;
        }
    }
    for (int i=1; i<=n; i++)
    {
        in >> s;
        for (int j=0; j<s.length(); j++)
        {
            if (s[j] == '*') a[i][j+1] = 1;
            if (s[j] == 'I')
            {
                a[i][j+1] = 2;
                start = {i, j+1};
            }
            if (s[j] == 'D')
            {
                a[i][j+1] = 3;
                q.push({i,j+1});
                d[i][j+1] = 0;
            }
            if (s[j] == 'O')
            {
                a[i][j+1] = 4;
                unde = {i, j+1};
            }
        }
    }
    BFS();
    if (d[unde.first][unde.second] == INF) out << "-1";
    else
    {
        int st = 1,dr = d[start.first][start.second],mij,sol = 1;

        while (st <= dr)
        {
            mij = (st + dr)/2;
            if (Check(mij))
            {
                sol = mij;
                st = mij + 1;
            }
            else dr = mij - 1;
        }
        out << sol;
    }
    return 0;
}