Cod sursa(job #2601300)

Utilizator ptudortudor P ptudor Data 14 aprilie 2020 12:16:35
Problema Barbar Scor 10
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.07 kb
#include <bits/stdc++.h>
#define INF 1000000005
#define ll long long
using namespace std;

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

ll n,m,cost[1005][1005],st_y,st_x,end_x,end_y,viz[1005][1005];
ll dy[4] = {0 , 0 , -1 , 1};
ll dx[4] = {1 , -1 , 0 , 0};
char a[1005][1005];
queue <pair<ll,ll>> q;

void Fill(ll i,ll j,ll lim)
{
    viz[i][j] = 1;
    for (ll k = 0; k < 4; k++)
    {
        ll y = i + dy[k];
        ll x = j + dx[k];
        if (y >= 1 && y <= n && x >= 1 && x <= m)
        if ( (a[y][x] == '.') && cost[y][x] >= lim && viz[y][x] == 0)
            Fill(y , x , lim);
    }
}
bool ver(ll lim)
{
    ll i,j;

    for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) viz[i][j] = 0;
    Fill(st_y , st_x , lim);


    if (viz[end_y][end_x] == 1) return true;
    return false;
}
ll solve(ll st, ll dr)
{
    ll mij,last = -1;
    bool f;
    while (st <= dr)
    {
        mij = (st + dr) / 2;
        f = ver(mij);
        if (f)
            last = mij,
            st = mij + 1;
        else
            dr = mij - 1;
    }
    return last;
}
int main()
{ll i,j;
    in >> n >> m;
    for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) in >> a[i][j];
    for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) cost[i][j] = INF;
    for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) {
        if (a[i][j] == 'D') q.push({i,j}) , cost[i][j] = 0;
        else if (a[i][j] == 'I') st_y = i , st_x = j;
        else if (a[i][j] == 'O') end_y = i , end_x = j;
    }

    while (!q.empty())
    {
        i = q.front().first;
        j = q.front().second;
        q.pop();

        for (int k = 0; k < 4; k++)
        {
            ll y = i + dy[k];
            ll x = j + dx[k];

            if (y >= 1 && y <= n && x >= 1 && x <= m)
            if (cost[y][x] > cost[i][j] + 1){
                q.push({y,x});
                cost[y][x] = cost[i][j] + 1;
            }
        }
    }
    if (ver(0) == 0) out << "-1\n";
    else
    out << solve(0 , n * m) << "\n";
    out.close();
    in.close();
    return 0;
}