Cod sursa(job #2297056)

Utilizator mircearoataMircea Roata Palade mircearoata Data 5 decembrie 2018 11:25:40
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda prega_casi_5.12.2018 Marime 2.6 kb
#include <queue>
#include <fstream>
#include <cstring>

using namespace std;

ifstream in("barbar.in");
ofstream out("barbar.out");
struct coord
{
    int x, y, cost;
};

queue <coord> q;

int l,c,begi,begj,endi,endj,b[1005][1005];
char a[1005][1005],v[1005][1005];

void lee()
{
    coord w,w2;
    int t;
    int dx[]= {-1,0,1,0};
    int dy[]= {0,1,0,-1};
    while(q.empty()==false)
    {
        w = q.front();
        q.pop();
        for(t = 0; t<4; t++)
        {
            w2.x = w.x+dx[t];
            w2.y = w.y+dy[t];
            w2.cost = w.cost+1;
            if(a[w2.x][w2.y]!='*')
                if(b[w2.x][w2.y]==0)
                {
                    q.push(w2);
                    b[w2.x][w2.y]=w2.cost;
                }
        }
    }
}

bool valid(int d)
{
    if(b[begi][begj]<=d)
        return false;
    memset(v,'0',sizeof(v));
    v[begi][begj]='1';
    while(!q.empty())
        q.pop();
    coord aux,w;
    int t;
    int dx[]= {-1,0,1,0};
    int dy[]= {0,1,0,-1};
    w.x = begi;
    w.y = begj;
    q.push(w);
    while(!q.empty())
    {
        w = q.front();
        q.pop();
        for(t = 0; t<4; t++)
        {
            aux.x = w.x+dx[t];
            aux.y = w.y+dy[t];
            if(a[aux.x][aux.y]!='*' && b[aux.x][aux.y]>d && v[aux.x][aux.y]!='1')
            {
                if(aux.x == endi && aux.y == endj)
                    return true;
                v[aux.x][aux.y]='1';
                q.push(aux);
            }
        }

    }
    return false;

}

int main()
{
    int sol=-1,st,dr,d;
    coord aux;
    in >> l >> c;
    for(int i = 1; i <= l; i++)
        in >> (a[i]+1);
    for(int i = 0; i <= c+1; i++)
        a[0][i] = a[l+1][i] = '*';
    for(int i = 0; i <= l+1; i++)
        a[i][0] = a[i][c+1] = '*';
    for(int i = 1; i <= l; i++)
        for(int j = 1; j <= c; j++)
            if(a[i][j] == 'I')
            {
                begi = i;
                begj = j;
            }
            else if(a[i][j] == 'O')
            {
                endi = i;
                endj = j;
            }
            else if(a[i][j] == 'D')
            {
                aux.x = i;
                aux.y = j;
                aux.cost = 1;
                q.push(aux);
                b[i][j] = 1;
            }
    lee();
    st = 0;
    dr = 1000;
    while(st <= dr)
    {
        d=(st+dr)>>1;
        if(valid(d))
        {
            sol = d;
            st = d+1;
        }
        else
            dr = d-1;
    }
    out << sol << "\n";
    return 0;
}