Cod sursa(job #1140383)

Utilizator lacraruraduRadu Matei Lacraru lacraruradu Data 11 martie 2014 22:51:52
Problema Barbar Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.47 kb
#include <fstream>
#include <queue>

using namespace std;

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

int m, n, i1, j1, i2, j2;

struct pozitie
{
    int lin,col;
};

char v[1001][1001];
int d[1001][1001];
int c[1001][1001];
queue <pozitie> q;

const int dlin[] = {-1,0,1,0};
const int dcol[] = {0,1,0,-1};

bool drum(int dist)
{
    int i, j;
    pozitie x, y;

    for(i = 1; i <= m; i++)
        for(j = 1; j <= n; j++)
            if(d[i][j] < dist)
                c[i][j] = -1;
            else
                c[i][j] = 0;

    c[i1][j1] = 1;
    c[i2][j2] = 0;
    q.push((pozitie){i1, j1});
    while(!q.empty() && c[i2][j2] != 1)
    {
        x = q.front();
        q.pop();

        for(i = 0; i < 4; i++)
        {
            y.lin = x.lin + dlin[i];
            y.col = x.col + dcol[i];

            if(v[y.lin][y.col] != NULL && c[y.lin][y.col] == 0)
            {
                c[y.lin][y.col] = 1;
                q.push(y);
            }
        }
    }
    while(!q.empty())
    {
        q.pop();
    }

    if(c[i2][j2] == 1)
        return 1;
    return 0;
}

int main()
{
    int i, j, pas;
    pozitie x, y;

    in>>m>>n;

    for(i = 1; i <= m; i++)
        in>>(1 + v[i]);

    for(i = 1; i <= m; i++)
        for(j = 1; j <= n; j++)
            if(v[i][j] == 'D')
            {
                d[i][j] = 1;
                q.push((pozitie){i,j});
            }
            else if(v[i][j] == 'I')
            {
                i1 = i;
                j1 = j;
            }
            else if(v[i][j] == 'O')
            {
                i2 = i;
                j2 = j;
            }

    while(!q.empty())
    {
        x = q.front();
        q.pop();
        for(i = 0; i < 4; i++)
        {
            y.lin = x.lin + dlin[i];
            y.col = x.col + dcol[i];
            if(v[y.lin][y.col] != NULL && d[y.lin][y.col] == 0)
            {
                d[y.lin][y.col] = 1 + d[x.lin][x.col];
                q.push(y);
            }
        }
    }

    for(i = 1; i <= m; i++)
        for(j = 1; j <= n; j++)
            if(v[i][j] == '*' || v[i][j] == 'D')
                d[i][j] = -1;
            else
                d[i][j]--;

    i = 0;
    pas = 1 << 19;
    while(pas)
    {

        if(drum(i + pas))
            i += pas;
        pas /= 2;
    }

    if(drum(i))
        out<<i<<'\n';
    else
        out<<-1<<'\n';
    return 0;
}