Cod sursa(job #2482382)

Utilizator pishcotMiruna Turbatu pishcot Data 28 octombrie 2019 10:44:21
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.63 kb
#include <bits/stdc++.h>

const int bomba = 2e9 + 1;

using namespace std;

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

int n, m,b[1005][1005], c[1005][1005];
char a[1005][1005];
int dx[] = {-1, 0, 0, 1};
int dy[] = {0, - 1,  1, 0};
queue<pair<int, int> > q;
int xi, yi, xf, yf;

void read()
{
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
        fin >> (a[i] + 1);
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
        {
            b[i][j] = bomba;

        }
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            if(a[i][j] == 'I')
            {
                xi = i;
                yi = j;
            }
            else if(a[i][j] == 'O')
            {
                xf = i;
                yf = j;
            }

}

void Init()
{
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            c[i][j] = bomba;
}

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

void Lee_dragoni()
{
    int x, y, i, j, k;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            if(a[i][j] == 'D')
            {
                b[i][j] = 1;
                q.push({i,j});

            }

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

bool Lee_Paftenie(int dist)
{
    Init();
    int x, y, i, j, k;
    c[xi][yi] = 0;
    q.push({xi,yi});
    while(!q.empty())
    {
        i = q.front().first;
        j = q.front().second;
        q.pop();
        for(k = 0; k <= 3; k++)
        {
            x = dx[k] + i;
            y = dy[k] + j;
            if(Check(x,y) && a[x][y] != '*' && b[x][y] > dist && c[x][y] >
                    c[i][j] + 1)
            {
                c[x][y] = c[i][j] + 1;
                q.push({x,y});
            }
        }
    }
    return !(c[xf][yf] == bomba);

}

void cautbin()
{
    int st, dr, mij, sol;
    st = 1;
    dr = 1000000;
    sol = -1;
    while(st <= dr)
    {
        mij = (st + dr) / 2;
        if(Lee_Paftenie(mij))
        {
            sol = mij;
            st = mij + 1;
        }
        else dr = mij - 1;
    }
    fout << sol << "\n";
}

int main()
{
    read();
    Lee_dragoni();

    cautbin();
    return 0;
}