Cod sursa(job #2266884)

Utilizator DordeDorde Matei Dorde Data 22 octombrie 2018 22:17:08
Problema Barbar Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.65 kb
#include <fstream>
#include <queue>
#include <iostream>
#include <map>
#include <bitset>

using namespace std;
ifstream f ("barbar.in");
ofstream g ("barbar.out");
int const NM = 1001 , di [] = {0 , 1 , 0 , -1} , dj [] = {1 , 0 , -1 , 0};
short d1 [NM][NM] , d2 [NM][NM] , n , m , I1 , I2;
char v [NM][NM];
queue <pair <int , int> > Q;
inline bool valid (int x , int y){
    return x > 0 && y > 0 && x <= n && y <= m;
}
bitset <NM> mark [NM];
inline void DF (int i , int j , int d){
    while (! Q . empty ())
        Q . pop ();
    Q . push (make_pair (i , j));
    while (! Q . empty ()){
        int x1 = Q . front () . first;
        int x2 = Q . front () . second;
        if (d2 [x1][x2] == d - 1)
            return;
        for(int o = 0 ; o < 4 ; ++ o){
            int x = x1 + di [o];
            int y = x2 + dj [o];
            if (valid (x , y) && ! d2 [x][y] && v [x][y] == '.'){
                d2 [x][y] = 1 + d2 [x1][x2];
                Q . push (make_pair (x , y));
            }
        }
        Q . pop ();
    }
}
inline bool check (int dist){
    int i  , j;
    for(i = 1 ; i <= n ; ++ i)
        for(j = 1 ; j <= m ; ++ j)
            d2 [i][j] = 0;
    for(i = 1 ; i <= n ; ++ i)
        for(j = 1 ; j <= m ; ++ j)
            if (v [i][j] == 'D')
                DF (i , j , dist);
    for(i = 1 ; i <= n ; ++ i){
        for(j = 1 ; j <= m ; ++ j)
            cout << d2 [i][j] << ' ' ;
        cout << '\n';
    }
    cout << '\n';
    while (! Q . empty ())
        Q . pop ();
    Q . push (make_pair (I1 , I2));
    for(i = 1 ; i <= n ; ++ i)
        for(j = 1 ; j <= m ; ++ j)
            mark [i][j] = 0;
    mark [I1][I2] = 1;
    while (! Q . empty ()){
        int x1 = Q . front () . first;
        int x2 = Q . front () . second;
        for(i = 0 ; i < 4 ; ++ i){
            int x = x1 + di [i];
            int y = x2 + dj [i];
            if (v [x][y] == 'O' && ! d2 [x][y])
                return true;
            if (valid (x , y) && ! d2 [x][y] && ! mark [x][y]){
                Q . push (make_pair (x , y));
                mark [x][y] = 1;
            }
        }
        Q . pop ();
    }
    return false;
}
int main()
{
    int i , j;
    f >> n >> m;
    for(i = 1 ; i <= n ; ++ i)
        f >> (v [i] + 1);
    for(i = 1 ; i <= n ; ++ i)
        for(j = 1 ; j <= m ; ++ j)
            if (v [i][j] == 'I'){
                I1 = i , I2 = j;
                break;
            }
    int pas = (1 << 10) , found = 0;
    while (pas){
        if (check (pas + found))
            found += pas;
        pas /= 2;
    }
    g << found << '\n';
    return 0;
}