Cod sursa(job #3306958)

Utilizator RaresPoinaruPoinaru-Rares-Aurel RaresPoinaru Data 15 august 2025 15:13:27
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.83 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("barbar.in");
ofstream fout ("barbar.out");
#define cin fin
#define cout fout

const int MAXN=510;
const int INF=2e9;

int n,m,xs,ys,d[MAXN][MAXN],xf,yf,a[MAXN][MAXN],b[MAXN][MAXN];
int d2[MAXN][MAXN];
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};

vector <pair <int,int>> v;
void init (){
    for (int i=1;i<=n;++i){
        for (int j=1;j<=m;++j){
            d[i][j]=INF;
        }
    }
    for (auto x:v){
        d[x.first][x.second]=0;
    }
}

bool inm (int x, int y){
    if (x>=1 and x<=n and y>=1 and y<=m) return true;
    return false;
}

void Lee (){
    queue <pair <int,int>> q;
    for (auto x:v){
        q.push (x);
    }
    while (!q.empty ()){
        int x=q.front ().first,y=q.front ().second;
        q.pop ();
        for (int i=0;i<4;++i){
            int nx=x+dx[i],ny=y+dy[i];
            if (inm (nx,ny) and d[nx][ny]==INF and a[nx][ny]==0){
                d[nx][ny]=d[x][y]+1;
                q.push ({nx,ny});
            }
        }
    }
}


bool solve (int x){
    for (int i=1;i<=n;++i){
        for (int j=1;j<=m;++j){
            b[i][j]=0;
        }
    }
    for (int i=1;i<=n;++i){
        for (int j=1;j<=m;++j){
            if (a[i][j]==1) b[i][j]=1;
            if (d[i][j]<x) b[i][j]=1;

        }

    }
    if (d[xs][ys]<x) return false;

    for (int i=1;i<=n;++i){
        for (int j=1;j<=m;++j){
            d2[i][j]=INF;
        }
    }
    queue <pair <int,int>> q;
    q.push ({xs,ys});
    d2[xs][ys]=0;
    while (!q.empty ()){
        int x=q.front ().first,y=q.front ().second;
        q.pop ();
        for (int i=0;i<4;++i){
            int nx=x+dx[i],ny=y+dy[i];
            if (inm (nx,ny) and d2[nx][ny]==INF and b[nx][ny]==0){
                d2[nx][ny]=d2[x][y]+1;
                q.push ({nx,ny});
            }
        }
    }

    return d2[xf][yf]!=INF;
}

int main()
{
    ios_base::sync_with_stdio (false);
    cin.tie (nullptr);

    cin >>n>>m;

    for (int i=1;i<=n;++i){
        string s;
        cin >>s;
        for (int j=0;j<m;++j){
            if (s[j]=='I'){
                xs=i,ys=j+1;
            }
            if (s[j]=='O'){
                xf=i,yf=j+1;
            }
            if (s[j]=='*'){
                a[i][j+1]=1;
            }
            if (s[j]=='D'){
                v.push_back ({i,j+1});
            }
        }
    }

    init ();
    Lee ();


    /*for (int i=1;i<=n;++i){
        for (int j=1;j<=m;++j){
            cout <<d[i][j]<<' ';
        }
        cout <<'\n';
    }*/

    int st=0,dr=n+m;

    while (st<=dr){
        int mij=(st+dr)/2;
        if (solve (mij)){
            st=mij+1;
        }
        else{
            dr=mij-1;
        }
    }

    cout <<dr;

    return 0;
}