Cod sursa(job #3321898)

Utilizator tomavladnicolae@gmail.comTomavlad [email protected] Data 11 noiembrie 2025 18:29:02
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.43 kb
#include <bits/stdc++.h>
#define oo 1000000000
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n, m, xs, ys,xd,yd;
char a[1003][1003];
int d[1003][1003];
int dx[] = { -1,0,1,0 };
int dy[] = { 0,1,0,-1 };
queue<pair<int, int>>Q;
stack < pair<int, int>>st;
bitset<1003>viz[1003];
void Bordare()
{
    int i;
    for (i = 0; i <= m + 1; i++)
        a[0][i] = a[n + 1][i] = '*';
    for (i = 0; i <= n + 1; i++)
        a[i][0] = a[i][m + 1] = '*';
}
void Lee()
{
    int x, y, i, j;
    while (!Q.empty())
    {
        x = Q.front().first;
        y = Q.front().second;
        Q.pop();
        for (int k = 0; k <= 3; k++)
        {
            i = x + dx[k];
            j = y + dy[k];
            if (a[i][j] != '*' and d[x][y] + 1 < d[i][j])
            {
                d[i][j] = d[x][y] + 1;
                Q.push({ i,j });
            }
        }
    }
}
void Fill(int G)
{
    int i,j,x,y;
    for (i = 1; i <= n; i++)
        viz[i].reset();
    st.push({ xs, ys });
    viz[xs][ys] = 1;
    while (!st.empty())
    {
        x = st.top().first;
        y = st.top().second;
        st.pop();
        for (int k = 0; k <= 3; k++)
        {
            i = x + dx[k];
            j = y + dy[k];
            if (a[i][j] != '*' and d[i][j] >= G and viz[i][j]==0)
            {
                viz[i][j] = 1;
                st.push({ i,j });
            }
        }
    }
}
void CautBin()
{
    int st, dr, mij, p;
    st = 1;
    dr = min(d[xs][ys], d[xd][yd]);
    p = -1;
    while (st <= dr)
    {
        mij = (st + dr) / 2;
        Fill(mij);
        if (viz[xd][yd] == 1)
        {
            p = mij;
            st = mij + 1;
        }
        else dr = mij - 1;
    }
    fout << p << "\n";
}
int main()
{
    int i,j;
    fin >> n >> m;
    for (i = 1; i <= n; i++)
        for (j = 1; j <= m; j++)
        {
            fin >> a[i][j];
            d[i][j] = oo;
            if (a[i][j] == 'I')
            {
                xs = i;
                ys = j;
                a[i][j] = '.';
            }
            else if (a[i][j] == 'O')
            {
                xd = i;
                yd = j;
                a[i][j] = '.';
            }
            else if (a[i][j] == 'D')
            {
                Q.push({ i,j }); d[i][j] = 0;
            }
        }
    Bordare();
    Lee();
    CautBin();
    return 0;
}