Cod sursa(job #3215088)

Utilizator zavragiudavid dragoi zavragiu Data 14 martie 2024 17:57:12
Problema Barbar Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.13 kb
#include <bits/stdc++.h>
using namespace std;

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

queue< pair<int, int> > q;
char a[1005][1005];
int b[1005][1005], d[1005][1005], n, m, x, y;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
const int oo = 1e9;
int ans = oo;

void Init(int a[1005][1005])
{
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            a[i][j] = oo;
}

void Lee()
{
    int i, j, x, y, p;
    while(!q.empty())
    {
        i = q.front().first;
        j = q.front().second;
        q.pop();
        for(p = 0; p < 4; p++)
        {
            x = i + dx[p];
            y = j + dy[p];
            if((a[x][y] == '.' || a[i][j] == 'O') && b[x][y] > b[i][j] + 1)
            {
                b[x][y] = b[i][j] + 1;
                q.push({i, j});
            }
        }
    }
}

void Leee(int i, int j)
{
    int x, y, p, t, maxi;
    d[i][j] = 0;
    q.push({i, j});
    while(!q.empty())
    {
        i = q.front().first;
        j = q.front().second;
        q.pop();
        maxi = -1;
        for(p = 0; p < 4; p++)
        {
            x = i + dx[p];
            y = j + dy[p];
            ans = min(ans, b[i][j]);
        }
        for(p = 0; p < 4; p++)
        {
            x = i + dx[p];
            y = j + dy[p]; 
            if(a[x][y] == '.' && b[x][y] >= ans && d[x][y] > d[i][j] + 1)
            {
                d[x][y] = d[i][j] + 1;
                q.push({x, y});
            }
        }
    }
}
int main()
{
    int i, j;
    fin >> n >> m;
    Init(b);
    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= m; j++)
        {
            fin >> a[i][j];
            if(a[i][j] == 'D')
            {
                q.push({i, j});
                b[i][j] = 0;
            }
            else if (a[i][j] == 'I')
            {
                x = i;
                y = j;
            }
        }
        fin.get();
    }
    Lee();   
    Leee(x, y);
    fout << ans;
    for(i = 1; i <= n; i++, cout << "\n")
        for(j = 1; j <= m; j++)
            cout << b[i][j] << " ";
    return 0;
}