Cod sursa(job #2664790)

Utilizator AvramDanielAvram Daniel AvramDaniel Data 29 octombrie 2020 12:56:53
Problema Barbar Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.4 kb
#include<bits/stdc++.h>
#define a first
#define b second
using namespace std;

int n,m;
char harta[1010][1010];
queue< pair < int, int > > q;
pair <int , int> curr, I, O;
bool viz[1010][1010];
int dist[1010][1010];

int row[4] = {0, -1,0,1};
int col[4] = {-1,0,1,0};



bool bfs(int x){
    for(int i = 1;i<=n;i++)
        for(int j = 1;j<=m;j++)
            viz[i][j] = 0;

    while(!q.empty()){
        q.pop();
    }

    viz[I.a][I.b] = 1;
    q.push(I);

    while(!q.empty() && !viz[O.a][O.b]){
        curr = q.front();
        //cout <<curr.a<< ' '<< curr.b<<'\n';
        for(int p = 0; p < 4;p++){

            int i = curr.a + row[p];
            int j = curr.b + col[p];

            if(!viz[i][j] && (i > 0) && (j > 0) && (i<=n) && (j<=m) && dist[i][j] >= x){

                viz[i][j] = 1;
                q.push({i, j});

            }
        }

        q.pop();
    }

    return viz[O.a][O.b];
}

int cautbin(int st, int dr){
    int mid;
    while (st <=dr){
        mid = (st +dr)/2;
        if(!bfs(mid) ){
            dr = mid-1;
        }
        else st = mid +1;
    }
    return dr;

}

int main(){

    ifstream cin("barbar.in");
    ofstream cout("barbar.out");

    cin>>n>>m;
    for(int i = 1;i<=n;i++){
        for(int j = 1;j<=m;j++){
            cin>>harta[i][j];
            viz[i][j] = 0;
            if(harta[i][j] == 'D'){
                dist[i][j] = 0;
                q.push({i,j});
                viz[i][j] = 1;
            }
            if(harta[i][j] == 'I'){
                I = {i,j};
                viz[i][j] = 1;
            }
            if(harta[i][j] == '*'){
                dist[i][j] = -1;
                viz[i][j] = 1;
            }
            if(harta[i][j] == 'O'){
                O = {i, j};
            }
        }
    }



    while(!q.empty()){

        curr = q.front();
        //cout<<curr.a<<' '<<curr.b<<':';
        for(int p = 0; p < 4;p++){

            int i = curr.a + row[p];
            int j = curr.b + col[p];

            if(!viz[i][j] && (i > 0) && (j > 0) && (i<=n) && (j<=m)){
                dist[i][j] = dist[curr.a][curr.b] + 1;
                viz[i][j] = 1;
                q.push({i, j});
               // cout<<i<<' '<<j<<", ";
            }
        }
      //  cout<<'\n';
        q.pop();
    }



    cout<<cautbin(1,n+1);



    return 0;
}