Cod sursa(job #1801304)

Utilizator saba_alexSabadus Alex saba_alex Data 8 noiembrie 2016 21:05:01
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.25 kb
#include <iostream>
#include <fstream>
#include <queue>
#define MAX 1010
#define x first
#define y second

using namespace std;

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

queue <pair <int, int> > D;
queue <int> qx, qy;

int d[MAX][MAX], mat[MAX][MAX], n, m, maxx=MAX, i, j;
bool v[MAX];
char c;
pair <int, int> st, fi;

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

void lee_D(){
    int a, b, aa, bb;
    while(!qx.empty()){
        a=qx.front();
        b=qy.front();
        qx.pop();
        qy.pop();
        for(int k=0; k<4; ++k){
            aa=a+dx[k];
            bb=b+dy[k];
            if(aa && bb && aa<=n && bb<=m && d[aa][bb]==0){
                d[aa][bb]=d[a][b]+1;
                qx.push(aa);
                qy.push(bb);
            }
        }
    }
}


bool lee(int val){
    int a, b, aa, bb;
    qx.push(st.x);
    qy.push(st.y);
    while(!qx.empty()){
        a=qx.front();
        b=qy.front();
        qx.pop();
        qy.pop();
        for(int k=0; k<4; ++k){
            aa=dx[k]+a;
            bb=dy[k]+b;
            if(aa && bb && aa<=n && bb<=m && mat[aa][bb]!=-1 && d[aa][bb]>=val && mat[aa][bb]!=val){
                mat[aa][bb]=val;
                qx.push(aa);
                qy.push(bb);
            }
        }
    }
    if(mat[fi.x][fi.y]==val)
        return 1;
    return 0;
}

int caut(int s, int d){
    if(s>d && v[d]==1)
        return d;
    else{
        if(s>d && v[m]==0)
            return -1;
        else{
            int m=(s+d)/2;
            v[m]=lee(m);
            if(v[m]==1)
                return caut(m+1,d);
            if(v[m]==0)
                return caut(s,m-1);
        }
    }
}

int main()
{
    fin>>n>>m;
    for(i=1; i<=n; ++i)
        for(j=1; j<=m; ++j){
            fin>>c;
            if(c=='*'){
                mat[i][j]=-1;
                d[i][j]=-1;
            }
            else
                mat[i][j]=0;
            if(c=='D'){
                qx.push(i);
                qy.push(j);
            }
            if(c=='I')
                st=make_pair(i,j);
            if(c=='O')
                fi=make_pair(i,j);
        }
    lee_D();
    fout<<caut(1,d[st.x][st.y]);
    return 0;
}