Cod sursa(job #3379541)

Utilizator kuzeacosmin kuzea Data 30 noiembrie 2026 22:29:31
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.08 kb
#include<bits/stdc++.h>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");

int dx[]={1,0,-1,0};
int dy[]={0,1,0,-1};
const int NMAX=1001;
int r,c,s=-1,st=1,dr=0,aux,sx,sy,fx,fy;
char a[NMAX][NMAX];
int d[NMAX][NMAX];
bool vi[NMAX][NMAX];
bool b;

bool inc(int x,int y){
if(x>=0 && x<r && y>=0 && y<c) return 1;
return 0;
}

void bfs(){
    int x,y,x1,y1;
    queue<pair<int,int>> q;

    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            if(a[i][j]=='D'){
                d[i][j]=0;
                vi[i][j]=1;
                q.push({i,j});
            }
            else
                d[i][j]=INT_MAX;
        }
    }

    while(!q.empty()){
        x=q.front().first;
         y=q.front().second;
         q.pop();
        for(int i=0;i<4;i++){
            x1=x+dx[i]; y1=y+dy[i];
            if(inc(x1,y1) && !vi[x1][y1] && a[x1][y1]!='*'){
                vi[x1][y1]=1;
                d[x1][y1]=min(d[x1][y1],d[x][y]+1);
                q.push({x1,y1});
            }
        }
    }

}

void dfs(int x,int y,int v){
    int x1,y1;
    vi[x][y]=1;
    for(int i=0;i<4;i++){
        x1=x+dx[i];
        y1=y+dy[i];
        if(inc(x1,y1) && !vi[x1][y1] && a[x1][y1]!='*'){
            if(d[x1][y1]>=v) dfs(x1,y1,v);
        }
    }
    if(x==fx && y==fy) b=1;
}

int main(){

    fin>>r>>c;
    fin.getline(a[0],NMAX);
    for(int i=0;i<r;i++)
        fin.getline(a[i],NMAX);

    bfs();

    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            if(a[i][j]=='I'){
                sx=i;
                sy=j;
            }
            else if(a[i][j]=='O'){
                fx=i;
                fy=j;
            }
            if(a[i][j]!='*')
                dr=max(dr,d[i][j]);
        }
    }


    while(st<=dr){
        aux=(st+dr)/2;
        b=0;
        memset(vi,0,sizeof(vi));
        if(d[sx][sy]>=aux)
            dfs(sx,sy,aux);
        if(b){
            s=aux;
            st=aux+1;
        }
        else
            dr=aux-1;
    }

    fout<<s;

}