Cod sursa(job #2366560)

Utilizator nicolaefilatNicolae Filat nicolaefilat Data 4 martie 2019 20:51:52
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda simulare04032019 Marime 2.67 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;
}
inline void lee(){
    while(coada.size()){
        int x = coada.front().first,y = coada.front().second;
        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;
                viz[xnou][ynou] = true;
                coada.push({xnou,ynou});
            }
        }
    }

}
inline 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});
    viz[startx][starty] = true;
    while(coada.size()){
        int x = coada.front().first,y = coada.front().second;
        if(x == finishx and y == finishy)
            return 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){
                viz[xnou][ynou] = true;
                coada.push({xnou,ynou});
            }
        }
    }
    return false;
}
inline int cautbin(){
    int pas = 1<<16,r = 0;
    while(pas){
        if(ok(r + pas))
            r += pas;
        pas /= 2;
    }
    if(!r)
        r = -1;
    return r;
}

int main()
{
    in.tie(NULL);
    out.tie(NULL);
    ios::sync_with_stdio(false);
    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});
                viz[i][j] = true;

            }
            else if(ch == 'O'){
                finishx = i;
                finishy = j;
            }
        }
    }
    /*n = m = 1000;
    coada.push({n,1});
    viz[n][1] = true;
    startx = starty = 1;
    finishx = finishy = n;*/
    lee();
    out<<cautbin();
    return 0;
}