Cod sursa(job #1843614)

Utilizator calinfloreaCalin Florea calinflorea Data 8 ianuarie 2017 22:36:54
Problema Barbar Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.64 kb
#include <bits/stdc++.h>
#define inf 1000005
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
char a[1005][1005];
int b[1005][1005], c[1005][1005], n, m, xs, ys, xf, yf;
queue <pair<int,int> >q;
void Citire()
{
    int i, j;
    fin >> n >> m;
    for(i = 1; i <= n; i++)
        for(j = 1; j <= n; j++)
        {
            fin >> a[i][j];
            b[i][j] = inf;
            if(a[i][j] == 'D')
            {
                q.push(make_pair(i, j));
                b[i][j] = 0;
            }
            else if(a[i][j] == 'I')
                xs = i, ys = j;
            else if(a[i][j] == 'O')
                xf = i, yf = j;
        }

}
void Bordare()
{
    int i;
    for(i = 0; i <= n + 1; i++)
        a[i][0] = a[i][m + 1] = '*';
    for(i = 0; i <= m + 1; i++)
        a[0][i] = a[n + 1][i] = '*';
}
void Initializare()
{
    int i, j;
    for(i = 1; i <= n; i++)
        for(j = 1; j <= m; j++)
            c[i][j] = inf;
}
void LeeDr()
{
    int x, y, i, j, k;
    int dx[] = {0, 0, -1, 1};
    int dy[] = {1, -1, 0, 0};
    while(!q.empty())
    {
        i = q.front().first;
        j = q.front().second;
        q.pop();
        for(k = 0; k < 4; k++)
        {
            x = i + dx[k];
            y = j + dy[k];
            if(a[x][y] != '*' && a[x][y] != 'D' && b[x][y] > b[i][j] + 1)
            {
                b[x][y] = b[i][j] + 1;
                q.push(make_pair(x,y));
            }
        }
    }
}

int LeeOm(int s)
{
    int i, j, x, y, k;
    int dx[] = {0, 0, 1, -1};
    int dy[] = {-1, 1, 0, 0};
    if(b[xs][ys] <= s)
        return 0;
    q.push(make_pair(xs, ys));
    c[xs][ys] = 0;
    while(!q.empty())
    {
        i = q.front().first;
        j = q.front().second;
        q.pop();
        for(k = 0; k < 4; k++)
        {
            x = i + dx[k];
            y = j + dy[k];
            if(a[x][y] != '*' && c[x][y] > c[i][j] + 1 && s <= b[x][y])
            {
                c[x][y] = c[i][j] + 1;
                q.push(make_pair(x, y));
            }
        }
    }
    if(c[xf][yf] != inf)
        return 1;
    return 0;
}
void CautaBin()
{
    int st = 0, dr = 1000000, mij, sf = -1;
    while(st <= dr)
    {
        mij = (st + dr) / 2;
        if(LeeOm(mij) == 1)
        {
            sf = mij;
            st = mij + 1;
            Initializare();
        }
        else
        {
            Initializare();
            dr = mij - 1;
        }
    }
    fout << sf << "\n";
}
int main()
{
    Citire();
    Bordare();
    Initializare();
    LeeDr();
    CautaBin();
    return 0;
}