Cod sursa(job #2366494)

Utilizator nicolaefilatNicolae Filat nicolaefilat Data 4 martie 2019 20:29:07
Problema Barbar Scor 40
Compilator cpp-64 Status done
Runda simulare04032019 Marime 2.3 kb
#include <iostream>
#include <fstream>
#include <queue>

const int MAXN = 1000 + 5;

const int dx[] = {-1,0,1,0};
const int dy[] = {0,1,0,-1};

using namespace std;

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

int n,m,v[MAXN][MAXN],dp[MAXN][MAXN];
bool viz[MAXN][MAXN];
int startx,starty,finishx,finishy;
queue<pair<int,int> >coada;

bool in_matrice(int x,int y){
    if(x >= 1 and x <= n and y >= 1 and y <= m)
        return true;
    return false;
}
void lee(){
    while(coada.size()){
        int x = coada.front().first,y = coada.front().second;
        viz[x][y] = true;
        coada.pop();
        for(int i = 0; i < 4; i++){
            int xnou = x + dx[i],ynou = y + dy[i];
            if(in_matrice(xnou,ynou) and !viz[xnou][ynou] and v[xnou][ynou] != -1){
                dp[xnou][ynou] = dp[x][y] + 1;
                coada.push({xnou,ynou});
            }
        }
    }
}
bool ok(int distanta){
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++)
            viz[i][j] = false;
    }
    while(coada.size())
        coada.pop();
    coada.push({startx,starty});
    while(coada.size()){
        int x = coada.front().first,y = coada.front().second;
        if(x == finishx and y == finishy)
            return true;
        viz[x][y] = true;
        coada.pop();
        for(int i = 0; i < 4; i++){
            int xnou = x + dx[i],ynou = y + dy[i];
            if(in_matrice(xnou,ynou) and !viz[xnou][ynou] and v[xnou][ynou] != -1 and dp[xnou][ynou] >= distanta)
                coada.push({xnou,ynou});
        }
    }
    return false;
}
int cautbin(){
    int pas = 1<<28,r = 0;
    while(pas){
        if(ok(r + pas))
            r += pas;
        pas /= 2;
    }
    return r;
}

int main()
{
    in>>n>>m;
    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++){
            char ch;
            in>>ch;
            if(ch == '*')
                v[i][j] = -1;
            else if(ch == 'I'){
                startx = i;
                starty = j;
            }
            else if(ch == 'D')
                coada.push({i,j});
            else if(ch == 'O'){
                finishx = i;
                finishy = j;
            }
        }
    }
    lee();
    out<<cautbin();
    return 0;
}