Cod sursa(job #2950122)

Utilizator emazareMazare Emanuel emazare Data 2 decembrie 2022 22:42:41
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.53 kb
#include<iostream>
#include <fstream>
#include <queue>

using namespace std;

ifstream fin("barbar.in");
ofstream fout("barbar.out");

queue<pair<int, int>> q;
char ch[1005][1005];
int acc[1005][1005];
bool vizitat[1005][1005];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int n,m,lp,cp,lf,cf;

bool valid(int a, int b){
    if(a>0 && b>0 && a<=n && b<=m && acc[a][b] == -1 && ch[a][b]!='*')
        return 1;
    else
        return 0;
}

bool valid1(int a, int b, int nr){
    if(a>0 && b>0 && a<=n && b<=m && vizitat[a][b] == 0 && acc[a][b]>=nr && ch[a][b]!='*')
        return 1;
    else
        return 0;
}

bool lee(int nr){
    if(acc[lp][cp]<nr)
        return 0;
    pair<int, int> pr = {lp, cp};
    int i,j,a,b;
    for(i=1;i<=n;i++){
        for(j=1;j<=m;j++)
            vizitat[i][j] = 0;
    }
    q.push(pr);
    vizitat[lp][cp] = 1;
    while(!q.empty()){
        for(i=0;i<4;i++){
            a = q.front().first+dx[i];
            b = q.front().second+dy[i];
            if(valid1(a, b, nr)){
                pr = {a, b};
                q.push(pr);
                vizitat[a][b] = 1;
            }
        }
        q.pop();
    }
    while(!q.empty())
        q.pop();
    return vizitat[lf][cf];
}

int main()
{
    int a,b,i,j,st,dr,mid,rez;
    pair<int, int> pr;
    fin >> n >> m;
    for(i=1;i<=n;i++){
        for(j=1;j<=m;j++){
            fin >> ch[i][j];
            if(ch[i][j] == 'I'){
                lp = i;
                cp = j;
                acc[i][j] = -1;
            }
            if(ch[i][j] == 'O'){
                lf = i;
                cf = j;
                acc[i][j] = -1;
            }
            if(ch[i][j] == 'D'){
                acc[i][j] = 0;
                pr = {i, j};
                q.push(pr);
            }
            if(ch[i][j] == '*' || ch[i][j] == '.')
                acc[i][j] = -1;
        }
    }
    while(!q.empty()){
        for(i=0;i<4;i++){
            a = q.front().first+dx[i];
            b = q.front().second+dy[i];
            if(valid(a, b)){
                pr = {a, b};
                q.push(pr);
                acc[a][b] = acc[a-dx[i]][b-dy[i]]+1;
            }
        }
        q.pop();
    }
    while(!q.empty())
        q.pop();
    rez = -1;
    st = 0;
    dr = 1000001;
    while(st<=dr){
        mid = (st+dr)/2;
        if(lee(mid)){
            st = mid+1;
            rez = mid;
        }
        else
            dr = mid-1;
    }
    fout << rez;
    return 0;
}