Cod sursa(job #3342869)

Utilizator rayenn3D Andra rayenn3 Data 25 februarie 2026 22:31:35
Problema Barbar Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.7 kb
#include <fstream>
#include <queue>
#define NMAX 1002

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

struct punct{
    int x, y;
};
queue <punct> q;

int a[NMAX + 2][NMAX + 2];
int dist[NMAX + 2][NMAX + 2];
int viz[NMAX + 2][NMAX + 2];

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

void dist_dragon(){
    int rez = -1;
    punct aux, nou;
    while(!q.empty()){
        aux = q.front();
        for(int dir = 0; dir < 4; dir++){
            nou.x = aux.x + dx[dir];
            nou.y = aux.y + dy[dir];
            if(a[nou.x][nou.y] == 0 && viz[nou.x][nou.y] != 1){
                dist[nou.x][nou.y] = dist[aux.x][aux.y] + 1;
                viz[nou.x][nou.y] = 1;
                q.push(nou);
            }
        }
        q.pop();
    }
}
int bfs(int var, int n, int m){
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            viz[i][j] = 0;
    bool ok = 0;
    punct aux, nou, st;
    st = q.front();
    viz[st.x][st.y] = 1;
    while(!q.empty()){
        aux = q.front();
        for(int dir = 0; dir < 4; dir++){
            nou.x = aux.x + dx[dir];
            nou.y = aux.y + dy[dir];
            if(dist[nou.x][nou.y] >= var && viz[nou.x][nou.y] != 1 && a[nou.x][nou.y] == 0){
                viz[nou.x][nou.y] = 1;
                q.push(nou);
            }
            if(a[nou.x][nou.y] == 3)
                ok = 1;
        }
        q.pop();
    }
    return ok;
}
int main()
{
    int n, m, st, dr, mij, cnt, last;
    char x;
    punct barbar, dragon;
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++){
            fin >> x;
            if(x == 'D'){
                a[i][j] = 1;
                dragon.x = i;
                dragon.y = j;
                q.push(dragon);
            }
            else if(x == '*')
                a[i][j] = -2;
            else if(x == 'I'){
                a[i][j] = 2;
                barbar.x = i;
                barbar.y = j;
            }
            else if(x == 'O')
                a[i][j] = 3;

        }
    //
     for(int i = 1; i <= n; i++)
        a[i][0] = a[i][m + 1] = -2;
    for(int j = 1; j <= m; j++)
        a[0][j] = a[n + 1][j] = -2;

    dist_dragon();

   /*for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m; j++)
            fout << dist[i][j] << ' ';
        fout << '\n';}*/
    //
    st = 1; dr = n + m - 2;
    while(st <= dr){
        mij = (st + dr) / 2;
        q.push(barbar);
        if(bfs(mij, n, m) == 1){
            st = mij + 1;
            last = mij;
        }
        else
            dr = mij - 1;
    }
    fout << last;
    return 0;
}