Cod sursa(job #1910885)

Utilizator valentinoMoldovan Rares valentino Data 7 martie 2017 18:43:54
Problema Barbar Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.8 kb
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <windows.h>
#define inf 0x3f3f3f3f

using namespace std;

struct point
{
    unsigned int x, y;
};

queue < pair < int, int > > q;
point start, finish;
int b[1005][1005], a[1005][1005], m, n;
char c;
int dx[4] = {-1,0,1,0}, dy[4] = {0,1,0,-1};

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

void Update()
{
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j)
        b[i][j] = 0;
}

void Read()
{
    f >> n >> m;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j)
        {
            f >> c;
            if(c == 'D')
            {
                a[i][j] = 1;
                q.push(make_pair(i, j));
            }
            else if(c == '*') a[i][j] = -1;
            else if(c == 'I')
            {
                start.x = i;
                start.y = j;
            }
            else if(c == 'O')
            {
                finish.x = i;
                finish.y = j;
            }
        }
}

void Lee()
{
    int startx, starty;
    while(!q.empty())
    {
        startx = q.front().first;
        starty = q.front().second;
        q.pop();
        for(int i = 0; i < 4; ++i)
        {
            if(1 <= startx + dx[i] && startx + dx[i] <= n && 1 <= starty + dy[i] && starty + dy[i] <= m)
                if(a[startx + dx[i]][starty + dy[i]] == 0)
                {
                    a[startx + dx[i]][starty + dy[i]] = a[startx][starty] + 1;
                    q.push(make_pair(startx + dx[i], starty + dy[i]));
                }
        }
    }
}

bool Solve(int k)
{
    Update();
    q.push(make_pair(start.x, start.y));
    int startx, starty;
    while(!q.empty())
    {
        startx = q.front().first;
        starty = q.front().second;
        q.pop();
        for(int i = 0; i < 4; ++i)
        {
            if(1 <= startx + dx[i] && startx + dx[i] <= n && 1 <= starty + dy[i] && starty + dy[i] <= m)
                if(a[startx + dx[i]][starty + dy[i]] >= k && !b[startx + dx[i]][starty + dy[i]])
                {
                    b[startx + dx[i]][starty + dy[i]] = b[startx][starty] + 1;
                    q.push(make_pair(startx + dx[i], starty + dy[i]));
                }
        }
    }
    return b[finish.x][finish.y] != 0;
}

int main()
{
    Read();
    Lee();
    int mij, st = 1, dr, sol = inf;
    dr = n * m + 1;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j)
        a[i][j]--;
    while(st <= dr)
    {
        mij = (st + dr) >> 1;
        if(Solve(mij))
        {
            sol = mij;
            st = mij + 1;
        }
        else dr = mij - 1;
    }
    if(sol != inf) g << sol << '\n';
    else g << "-1" << '\n';
}