Cod sursa(job #1425581)

Utilizator VictorDumitrescuDumitrescu Victor VictorDumitrescu Data 27 aprilie 2015 18:48:21
Problema Barbar Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.77 kb
#include <iostream>
#include <stdio.h>
#define M 1003
using namespace std;

FILE *f, *g;
int d[M][M], p1, p2, u1 = -1, u2 = 0, r, c;
char a[M][M];
int dlin[] = {-1, 0, 1, 0};
int dcol[] = {0, 1, 0, -1};
struct poz
{
    int lin, col;
};
poz q1[M*M], q2[M*M];
bool sepoate[M][M];
void lee1()
{
    poz x, y;
    while(p1 <= u1)
    {
        x = q1[p1++];
        for(int i = 0; i <= 3; i++)
        {
            y.lin = x.lin + dlin[i];
            y.col = x.col + dcol[i];
            if(d[y.lin][y.col] == 0)
            {
                d[y.lin][y.col] = 1 + d[x.lin][x.col];
                q1[++u1] = y;
            }
        }
    }
    return;
}

void bordare(int a, int b)
{
    for(int i = 0; i <= a + 1; i++)
        d[i][0] = d[i][b + 1] = -3;
    for(int i = 0; i <= b + 1; i++)
        d[0][i] = d[a + 1][i] = -3;
}

bool se_poate(int w)
{
    poz x, y;

    u2 = 1;
    p2 = 1;
    for(int i = 1; i <= r; i++)
        for(int j = 1; j <= c; j++)
            sepoate[i][j] = 0;
    if(d[q2[1].lin][q2[1].col] < w)
        return false;
    sepoate[q2[1].lin][q2[1].col] = 1;
    while (p2 <= u2)
    {
        x = q2[p2++];
        for(int i = 0; i <= 3; i++)
        {
            y.lin = x.lin + dlin[i];
            y.col = x.col + dcol[i];
            if(a[y.lin][y.col] == '.' && d[y.lin][y.col] >= w && sepoate[y.lin][y.col] == 0)
            {
                q2[++u2] = y;
                sepoate[y.lin][y.col] = 1;

            }
            if(a[y.lin][y.col] == 'O')
                    return true;
        }
    }
    return false;
}
int cb()
{
    int i = 0, pas = 1 << 19;
    while (pas != 0)
    {
        if (se_poate(i+pas))
            i += pas;
        pas /= 2;
    }
    return i - 1;
}
int main()
{   int i, j;
    f = fopen("barbar.in", "r");
    fscanf(f, "%d%d\n", &r ,&c);
    for(i = 1; i <= r; i++)
    {
        fgets(1 + a[i], M, f);
    }
    for(i = 1; i <= r; i++)
        for(j = 1; j <= c; j++)
        {
            if(a[i][j] == '*')
                d[i][j] = -3;
            if(a[i][j] == 'I')
            {
                //d[i][j] = -1;
                q2[1] = (poz){i, j};
            }
            //if(a[i][j] == 'O')
                //d[i][j] = -2;
            if(a[i][j] == 'D')
            {
                d[i][j] = 1;
                q1[++u1] = (poz){i, j};
            }
        }
    fclose(f);
    bordare(r,c);
    lee1();
    int rasp = cb();
    g = fopen("barbar.out", "w");
   /* for(i = 1; i <= r; i++){
        for(j = 1; j <= c; j++)
                fprintf(g,"%3d", d[i][j]);
        fprintf(g, "\n");
    }*/
    if(rasp > 1)
        fprintf(g, "%d\n", rasp);
    else fprintf(g, "%d\n", "-1");
    fclose(g);
    return 0;
}