Cod sursa(job #1932822)

Utilizator borcanirobertBorcani Robert borcanirobert Data 20 martie 2017 10:00:36
Problema Barbar Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.63 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;

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

const int MAX = 1005;
const int Inf = 0x3f3f3f3f;
const int di[] = { -1, 0, 1, 0 };
const int dj[] = { 0, 1, 0, -1 };
struct Cel{
    int i, j, c;

    bool operator < ( const Cel& a ) const
    {
        return c < a.c;
    }
};
int N, M;
int a[MAX][MAX];
string s;
int d[MAX][MAX];
int c[MAX][MAX];
queue< pair<int, int> > Q;
int x1, y1, x2, y2;

void Read();
void Dragoni();
void Solve();
bool OK( int i, int j );

int main()
{
    Read();
    Dragoni();
    Solve();

    fin.close();
    fout.close();
    return 0;
}

void Read()
{
    fin >> N >> M;
    memset(d, Inf, sizeof(d));
    for ( int i = 1; i <= N; ++i )
    {
        fin >> s;
        for ( int j = 0; j < M; ++j )
        {
            if ( s[j] == '*' )
                a[i][j + 1] = -1;
            if ( s[j] == 'D' )
            {
                d[i][j + 1] = 0;
                Q.push({i, j + 1});
            }
            if ( s[j] == 'I' )
                x1 = i, y1 = j + 1;
            if ( s[j] == 'O' )
                x2 = i, y2 = j + 1;
        }
    }
}

void Dragoni()
{
    while ( !Q.empty() )
    {
        int i = Q.front().first;
        int j = Q.front().second;
        Q.pop();

        for ( int k = 0; k < 4; ++k )
        {
            int iv = i + di[k];
            int jv = j + dj[k];

            if ( OK(iv, jv) && d[iv][jv] > d[i][j] + 1 && a[iv][jv] != -1 )
            {
                d[iv][jv] = d[i][j] + 1;
                Q.push({iv, jv});
            }
        }
    }

   /* for ( int i = 1; i <= N; ++i )
    {
        for ( int j = 1; j <= M; ++j )
            fout << d[i][j] << ' ';
        fout << '\n';
    }   */
}

void Solve()
{
    priority_queue<Cel> Q;
    memset( c, 0, sizeof(c) );
    c[x1][y1] = d[x1][y1];
    Q.push({x1, y1, d[x1][y1]});

    while ( !Q.empty() )
    {
        int i = Q.top().i;
        int j = Q.top().j;
        int cost = Q.top().c;
        Q.pop();

        if ( cost > c[i][j] ) continue;
        for ( int k = 0; k < 4; ++k )
        {
            int iv = i + di[k];
            int jv = j + dj[k];

            if ( OK( iv, jv ) && c[iv][jv] < min(c[i][j], d[iv][jv]) && a[iv][jv] != -1 )
            {
                c[iv][jv] = min(c[i][j], d[iv][jv]);
                Q.push({iv, jv, c[iv][jv]});
            }
        }
    }

    fout << c[x2][y2] << '\n';
}

bool OK( int i, int j )
{
    return i >= 1 && i <= N && j >= 1 && j <= M;
}