Cod sursa(job #2243674)

Utilizator i.uniodCaramida Iustina-Andreea i.uniod Data 21 septembrie 2018 10:07:06
Problema Barbar Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.41 kb
#include <fstream>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n, m, v[1002][1002], vlee[1002][1002];
queue <pair<int,int> > coada;
int dx[]={-1,0,1,0}, dy[]={0,1,0,-1}, maxi;
int xi, yi, xf, yf;
char s[1002];

void Citire()
{

    fin>>n>>m;
    fin.get();
    for(int i=1; i<=n; ++i) {
        fin.getline(s,sizeof(s));
        for(int j=0; j<m; ++j) {
            if(s[j]=='D') {
                v[i][j+1]=-1;
                coada.push(make_pair(i,j+1));
            }
            if(s[j]=='*')
                vlee[i][j+1]=v[i][j+1]=-1;
            if(s[j]=='I') {
                xi=i;
                yi=j+1;
            }
            if(s[j]=='O') {
                xf=i;
                yf=j+1;
            }
        }
    }
}

bool Verif(int x, int y)
{
    if(1>x || 1>y || x>n || y>m)
        return false;
    return true;
}

void LeeDr()
{
    int x, y, xx, yy;
    while(!coada.empty()) {
        x=coada.front().first;
        y=coada.front().second;
        coada.pop();
        for(int i=0; i<4; ++i) {
            xx=x+dx[i];
            yy=y+dy[i];
            if(vlee[xx][yy]==0 && Verif(xx,yy) ) {
                coada.push(make_pair(xx,yy));
                vlee[xx][yy]=vlee[x][y]+1;
                maxi=max(maxi,vlee[xx][yy]);
            }
        }
    }
}

bool Lee(int dist)
{
    coada.push(make_pair(xi,yi));
    int x, y, xx, yy;
    while(!coada.empty()) {
        x=coada.front().first;
        y=coada.front().second;
        coada.pop();
        for(int i=0; i<4; ++i) {
            xx=x+dx[i];
            yy=y+dy[i];
            if(v[xx][yy]==0 && vlee[xx][yy]>=dist && Verif(xx,yy)) {
                coada.push(make_pair(xx,yy));
                v[xx][yy]=v[x][y]+1;
            }
        }
    }
    if(v[xf][yf]!=0)
        return true;
    return false;
}

void Sterge()
{
    for(int i=1; i<=n; ++i)
        for(int j=1; j<=m; ++j)
            if(v[i][j]>0)
                v[i][j]=0;
}

void BS(int p, int u)
{
    int mij, sol;
    while(p<=u) {
        mij=(p+u)/2;
        if(Lee(mij))
            p=mij+1, sol=mij;
        else
            u=mij-1;
        Sterge();
    }
    if(Lee(sol))
        fout<<sol<<'\n';
    else
        fout<<-1<<'\n';
}

int main()
{
    Citire();
    LeeDr();
    BS(1, maxi);
    return 0;
}