Cod sursa(job #1947340)

Utilizator ionutpop118Pop Ioan Cristian ionutpop118 Data 30 martie 2017 21:50:32
Problema Barbar Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.32 kb
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int INF = 10000000;
struct point
{
    int x, y;
};
queue <point> q;
char a[1005][1005], stx, sty;
int d[1005][1005], finx, finy;
bool viz[1005][1005];
int dx[] = {0, -1, 0, 1, 0};
int dy[] = {0, 0, 1, 0, -1};
bool bfs(int x)
{
    point aux, nou;

    memset(viz, 0, sizeof(viz));
    while (!q.empty())
        q.pop();

    aux.x = stx; aux.y = sty;
    viz[stx][sty] = 1;
    q.push(aux);

    while (!q.empty())
    {
        aux = q.front();
        if (aux.x == finx && aux.y == finy)
            return 1;

        for (int i = 1; i <= 4; ++i)
        {
            nou.x = aux.x + dx[i];
            nou.y = aux.y + dy[i];
            if ((d[nou.x][nou.y] >= x || d[nou.x][nou.y] == -1)&& viz[nou.x][nou.y] == 0)
            {
                viz[nou.x][nou.y] = 1;
                q.push(nou);
            }
        }
        q.pop();
    }

    return 0;
}
int main()
{
    freopen("barbar.in", "r", stdin);
    freopen("barbar.out", "w", stdout);
    int n, m, st, dr, last, med;
    point aux, nou;
    scanf("%d %d\n", &n, &m);
    for (int i = 1; i <= n; ++i)
        gets(a[i] + 1);
    memset(d, -1, sizeof(d));
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= m; ++j)
            if (a[i][j] == 'D')
            {
                aux.x = i;
                aux.y = j;
                d[i][j] = 0;
                q.push(aux);
            }
            else if (a[i][j] == 'I')
                stx = i, sty = j;
            else if (a[i][j] == 'O')
                finx = i, finy = j;

    while(!q.empty())
    {
        aux = q.front();
        for (int i = 1; i <= 4; ++i)
        {
            nou.x = aux.x + dx[i];
            nou.y = aux.y + dy[i];
            if (a[nou.x][nou.y] != '*' && a[nou.x][nou.y] != 0 && d[nou.x][nou.y] == -1)
            {
                d[nou.x][nou.y] = d[aux.x][aux.y] + 1;
                q.push(nou);
            }
        }
        q.pop();
    }
    st = 0; last = -1; dr = INF;
    while (st <= dr)
    {
        med = (st + dr) / 2;
        if (bfs(med))
        {
            last = med;
            st = med + 1;
        }
        else
            dr = med - 1;
    }
    printf("%d\n", last);
    return 0;
}