Cod sursa(job #1702153)

Utilizator oldatlantianSerban Cercelescu oldatlantian Data 14 mai 2016 16:54:56
Problema Barbar Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.13 kb
#include <bits/stdc++.h>
using namespace std;

const int LMAX = 1005;
const int   SM = 1<<11;

struct APOZ {
    int x, y;
};

struct BPOZ {
    int x, y, val;
};

int r, c, sx, sy;
char mx[LMAX][LMAX];
int dst[LMAX][LMAX],
    aux[LMAX][LMAX];

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

void init(void) {
    int x, y, nx, ny, val;
    queue<BPOZ> q;

    for(int i=1; i<=r; ++i) {
        for(int j=1; j<=c; ++j) {
            if(mx[i][j]=='D') {
                q.push({i, j, 1});
                dst[i][j] = 1;
            }
            if(mx[i][j]=='I') {
                sx = i;
                sy = j;
            }
        }
    }

    while(!q.empty()) {
        x   = q.front().x;
        y   = q.front().y;
        val = q.front().val;
        q.pop();

        for(int i=0; i<4; ++i) {
            nx = x + dx[i];
            ny = y + dy[i];

            if(nx<1 || nx>r || ny<1 || ny>c || dst[nx][ny] || mx[nx][ny]=='*')
                continue;

            dst[nx][ny] = val+1;
            q.push({nx, ny, val+1});
        }
    }
}

bool check(int d) {
    queue<APOZ> q;
    int x, y, nx, ny;

    q.push({sx, sy});
    dst[sx][sy] = d;

    while(!q.empty()) {
        x = q.front().x;
        y = q.front().y;
        q.pop();

        if(mx[x][y]=='O')
            return true;

        for(int i=0; i<4; ++i) {
            nx = x + dx[i];
            ny = y + dy[i];

            if(nx<1 || nx>r || ny<1 || ny>c || dst[nx][ny]<=d || aux[nx][ny]==d || mx[nx][ny]=='*')
                continue;

            aux[nx][ny] = d;
            q.push({nx, ny});
        }
    }

    return false;
}

int main(void) {
    FILE *fi = fopen("barbar.in", "r");
    FILE *fo = fopen("barbar.out", "w");
    int ans;

    ans = 0;

    fscanf(fi,"%d%d ",&r,&c);
    for(int i=1; i<=r; ++i)
        fgets(mx[i]+1, 1001, fi);

    init();

    for(int m=SM; m; m>>=1)
        if(check(ans|m))
            ans|=m;

    if(!ans)
        fprintf(fo,"-1\n");
    else
        fprintf(fo,"%d\n",ans);

    fclose(fi);
    fclose(fo);
    return 0;
}