Cod sursa(job #2512727)

Utilizator ptudortudor P ptudor Data 21 decembrie 2019 14:45:44
Problema Barbar Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.94 kb
#include <bits/stdc++.h>
#define INF 1000000005
using namespace std;

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

int n,m,cost[1005][1005],st_y,st_x,end_x,end_y,viz[1005][1005];
int dy[4] = {0 , 0 , -1 , 1};
int dx[4] = {1 , -1 , 0 , 0};
char a[1005][1005];
queue <pair<int,int>> q;

void Fill(int i,int j,int lim)
{
    viz[i][j] = 1;
    for (int k = 0; k < 4; k++)
    {
        int y = i + dy[k];
        int x = j + dx[k];
        if ( (a[y][x] == '.' || a[y][x] == 'O') && cost[y][x] >= lim && viz[y][x] == 0)
            Fill(y , x , lim);
    }
}
bool ver(int lim)
{
    int i,j;

    for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) viz[i][j] = 0;
    Fill(st_y , st_x , lim);

    if (viz[end_y][end_x] == 1) return true;
    return false;
}
int solve(int st, int dr)
{
    int mij,last = 0;
    bool f;
    while (st <= dr)
    {
        mij = (st + dr) / 2;
        f = ver(mij);
        if (f)
            last = mij,
            st = mij + 1;
        else
            dr = mij - 1;
    }
    return last;
}
int main()
{int i,j;
    in >> n >> m;
    for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) in >> a[i][j];
    for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) cost[i][j] = INF;
    for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) {
        if (a[i][j] == 'D') q.push({i,j}) , cost[i][j] = 0;
        else if (a[i][j] == 'I') st_y = i , st_x = j;
        else if (a[i][j] == 'O') end_y = i , end_x = j;
    }

    while (!q.empty())
    {
        i = q.front().first;
        j = q.front().second;
        q.pop();

        for (int k = 0; k < 4; k++)
        {
            int y = i + dy[k];
            int x = j + dx[k];

            if (cost[y][x] > cost[i][j] + 1){
                q.push({y,x});
                cost[y][x] = cost[i][j] + 1;
            }
        }
    }

    out << solve(1 , n * m) << "\n";

    out.close();
    in.close();
    return 0;
}