Cod sursa(job #3281447)

Utilizator yellowGreenFatu Mihai yellowGreen Data 1 martie 2025 17:19:29
Problema Barbar Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.99 kb
#include <fstream>
#include <queue>
using namespace std;
ifstream cin("barbar.in");
ofstream cout("barbar.out");
int n,m,A[1005][1005],D[1005][1005],B[1005][1005];
int i1,j1,i2,j2;
int di[]={-1,0,1,0};
int dj[]={0,-1,0,1};
struct idx{int i,j;};
bool inside(int i,int j)
{
    return i>=1 && i<=n && j>=1 && j<=m;
}
bool check(int x)
{
    queue<idx> Q,bk;
    Q.push({i1,j1});
    bk.push({i1,j1});
    B[i1][j1]=1;
    while(!Q.empty())
    {
        int i=Q.front().i;
        int j=Q.front().j;
        Q.pop();
        for(int d=0;d<4;d++)
        {
            int iv=i+di[d];
            int jv=j+dj[d];
            if(inside(iv,jv) && B[iv][jv]==0 && D[iv][jv]>=x)
            {
                B[iv][jv]=1;
                Q.push({iv,jv});
                bk.push({iv,jv});
            }
        }
    }
    int ans=B[i2][j2];
    while(!bk.empty())
    {
        int i=bk.front().i;
        int j=bk.front().j;
        bk.pop();
        B[i][j]=0;
    }
    return ans;
}
void cb()
{
    int st=0,dr=1e6,ans=0;
    while(st<=dr)
    {
        int mij=(st+dr)>>1;
        if(check(mij))
        {
            ans=mij;
            st=mij+1;
        }
        else dr=mij-1;
    }
    if(ans==1) cout<<"-1";
    else cout<<ans-1;
}
int main()
{
    queue<idx> Q;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            char c;
            cin>>c;
            if(c=='I') i1=i,j1=j;
            if(c=='O') i2=i,j2=j;
            if(c=='*') A[i][j]=1;
            if(c=='D') Q.push({i,j}),D[i][j]=1;
        }
    }
    while(!Q.empty())
    {
        int i=Q.front().i;
        int j=Q.front().j;
        Q.pop();
        for(int d=0;d<4;d++)
        {
            int iv=i+di[d];
            int jv=j+dj[d];
            if(inside(iv,jv) && D[iv][jv]==0)
            {
                D[iv][jv]=D[i][j]+1;
                Q.push({iv,jv});
            }
        }
    }
    cb();
    return 0;
}