Cod sursa(job #3152634)

Utilizator Alex_BerbescuBerbescu Alexandru Alex_Berbescu Data 25 septembrie 2023 22:52:02
Problema Barbar Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.63 kb
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("fast-math")
#include<bits/stdc++.h>
using namespace std;
int st = 1, dr, mid, sol = -1, dist[1005][1005], n, m, mat[1005][1005], ok,  linfin, colfin, linst, colst, mindist[1005][1005];
char c;
bitset<1005>viz[1005];
bool inmat(int x, int y)
{
    return x >= 1 && x <= n && y >= 1 && y <= m;
}
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
queue<pair<int, int> >drg;
void mind()
{
    while(!drg.empty())
    {
        int x = drg.front().first;
        int y = drg.front().second;
        drg.pop();
        for(int d = 0; d < 4; ++d)
        {
            int inou = x + dx[d];
            int jnou = y + dy[d];
            if(inmat(inou, jnou) && mat[inou][jnou] != -1 && mindist[inou][jnou] == 0)
            {
                drg.push({inou, jnou});
                mindist[inou][jnou] = mindist[x][y] + 1;
            }
        }
    }
}
bool verif(int d)
{
    if(mindist[linst][colst] <= d)
    {
        return 0;
    }
     memset(dist, 0, sizeof dist);
    queue<pair<int, int> >q;
    q.push({linst, colst});
    while(!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for(int d = 0; d < 4; ++d)
        {
            int inou = x + dx[d];
            int jnou = y + dy[d];
            if(inmat(inou, jnou) && mat[inou][jnou] != -1 && mindist[inou][jnou] > d && dist[inou][jnou] == 0)
            {
                q.push({inou, jnou});
                dist[inou][jnou] = dist[x][y] + 1;
            }
        }
    }
    if(dist[linfin][colfin] > 0)
    {
        return 1;
    }
    return 0;
}
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int32_t main(int argc, char * argv[])
{
    fin >> n >> m;
    for(int i = 1; i <= n; ++i)
    {
        for(int j = 1; j <= m; ++j)
        {
            fin >> c;
            if(c == '*')
            {
                mat[i][j] = -1;
            }
            if(c == 'D')
            {
                drg.push({i, j});
                mat[i][j] = -1;
                mindist[i][j] = 1;
            }
            if(c == 'O')
            {
                linfin = i, colfin = j;
            }
            if(c == 'I')
            {
                linst = i, colst = j;
            }
        }
    }
    mind();
    st = 1,dr = n * m + 2;
    while(st <= dr)
    {
        mid = (st + dr) / 2;
        if(verif(mid))
        {
            sol = mid;
            st = mid + 1;
        }
        else
        {
            dr = mid - 1;
        }
    }
    if(sol == -1)
    {
        fout << -1;
    }
    else
    {
        fout << sol;
    }
    return 0;

}