Cod sursa(job #3342728)

Utilizator tomavladnicolae@gmail.comTomavlad [email protected] Data 25 februarie 2026 14:24:02
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.24 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("barbar.in"); 
ofstream fout("barbar.out");
int n, m, xs, ys, xf, yf;
char a[1005][1005];
int d[1005][1005],sol[1005][1005];
deque<pair<int, int>>Q;
bitset<1001>b[1001];
int dx[] = { -1,0,1,0 };
int dy[] = { 0,1,0,-1 };
void Lee()
{
    int val,x, y, i, j;
    while (!Q.empty())
    {
        x = Q.front().first;
        y = Q.front().second;
        Q.pop_front();
        for (int p = 0; p <= 3; p++)
        {
            i = dx[p] + x;
            j = dy[p] + y;
            val = d[x][y] + 1;
            if (a[i][j] != '*' and i >= 1 and i <= n and j >= 1 and j <= m and val < d[i][j])
            {
                d[i][j] = val;
                if (val <= d[Q.front().first][Q.front().second])
                    Q.push_front({ i,j });
                else Q.push_back({ i,j });
            }
        }
    }
}
void Fill(int G)
{
    int x, y, i, j;
    Q.push_back({ xs,ys });
    b[xs][ys] = 1;
    while (!Q.empty())
    {
        x = Q.front().first;
        y = Q.front().second;
        Q.pop_front();
        for (int p = 0; p <= 3; p++)
        {
            i = dx[p] + x;
            j = dy[p] + y;
            if (i >= 1 and i <= n and j >= 1 and j <= m and d[i][j] >= G and b[i][j]==0)
            {
                b[i][j] = 1;
                Q.push_front({ i,j });
            }
        }
    }
}
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] = 1e9;
            sol[i][j] = 1e9;
            if (a[i][j] == 'I') { xs = i; ys = j; }
            if (a[i][j] == 'O') { xf = i; yf = j; }
            if (a[i][j] == 'D') { Q.push_back({ i,j }); d[i][j] = 0; }
        }
    Lee();
    int mij, st, dr, p;
    st = 1;
    p = -1;
    dr = 1000000;
    if (d[xf][yf] == 1e9) { fout << -1; return 0; }
    while (st <= dr)
    {
      //  cout << 1;
        mij = (st + dr) / 2;
        for (i = 1; i <= n; i++)b[i].reset();
        Fill(mij);
        if (b[xf][yf] == 1)
        {
            p = mij;
            st = mij + 1;
        }
        else dr = mij - 1;
    }
    fout << p;
   return 0;
}