Cod sursa(job #2149135)

Utilizator moltComan Calin molt Data 2 martie 2018 12:36:08
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.58 kb
#include <bits/stdc++.h>

using namespace std;

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

struct cord
{
    int l,c;
};
const int NMAX = 1002,dl[] = {-1,0,1,0},dc[] = {0,1,0,-1};
cord q[NMAX * NMAX + 10],vecin,curent;
int n,m,mat[NMAX][NMAX],d[NMAX][NMAX],lp,cp,lu,cu,st,dr = -1,aux[NMAX][NMAX];
char ch;

void bordare()
{
    for (int i = 0; i <= n + 1; ++i)
        d[i][0] = d[i][m + 1] = 1;
    for (int j = 0; j <= m + 1; ++j)
        d[0][j] = d[n + 1][j] = 1;
}

bool uberprufen(int dist)
{
    st = 0;
    dr = -1;
    q[++dr].l = lp;
    q[dr].c = cp;
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= m; ++j)
            aux[i][j] = -1;
    aux[lp][cp] = 0;
    while (st <= dr)
    {
        curent = q[st++];
        for (int i = 0; i < 4; ++i)
        {
            vecin.l = curent.l + dl[i];
            vecin.c = curent.c + dc[i];
            if (aux[vecin.l][vecin.c] == -1 && d[vecin.l][vecin.c] >= dist)
            {
                q[++dr] = vecin;
                aux[vecin.l][vecin.c] = 1 + aux[curent.l][curent.c];
            }
        }
    }
    if (aux[lu][cu] != -1)
        return true;
    return false;
}

int binare_suche()
{
    int r = 0,pas = 1 << 12;
    while (pas != 0)
    {
        if (uberprufen(r + pas) == true && r + pas <= min(d[lp][cp],d[lu][cu]))
            r += pas;
        pas /= 2;
    }
    if (r == 0)
        return -1;
    return r;
}

int main()
{
    in>>n>>m>>ws;
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 1; j <= m; ++j)
        {
            in>>ch;
            if (ch == '.')
                d[i][j] = -1;
            else if (ch == 'D')
            {
                q[++dr].l = i;
                q[dr].c = j;
            }
            else if (ch == 'I')
            {
                lp = i;
                cp = j;
                d[i][j] = -1;
            }
            else if (ch == 'O')
            {
                lu = i;
                cu = j;
                d[i][j] = -1;
            }
            else if (ch == '*')
                d[i][j] = 1;
        }
        in>>ws;
    }
    bordare();
    while (st <= dr)
    {
        curent = q[st++];
        for (int i = 0; i < 4; ++i)
        {
            vecin.l = curent.l + dl[i];
            vecin.c = curent.c + dc[i];
            if (d[vecin.l][vecin.c] == -1)
            {
                d[vecin.l][vecin.c] = d[curent.l][curent.c] + 1;
                q[++dr] = vecin;
            }
        }
    }
    out<<binare_suche();
    return 0;
}