Cod sursa(job #1025302)

Utilizator maritimCristian Lambru maritim Data 9 noiembrie 2013 19:36:49
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.33 kb
#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
using namespace std;

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

#define MaxN 1010
#define Xn (Q.front().first+X[k])
#define Yn (Q.front().second+Y[k])

int N,M,Xs,Ys,Xf,Yf,Max;
int X[] = {0,-1,0,1,0}, Y[] = {0,0,1,0,-1};
char S[MaxN][MaxN];
int B[MaxN][MaxN],Best[MaxN][MaxN];
vector<pair<int,int> > List[3*MaxN]; 
int inLista[MaxN][MaxN];

void citire(void)
{
    f >> N >> M;
    for(int i=1;i<=N;i++)
        f >> (S[i]+1);
}

void Lee(void)
{
    queue<pair<int,int> > Q;

    for(int i=1;i<=N;++i)
        for(int j=1;j<=M;++j)
            if(S[i][j] == 'D')
                Q.push(make_pair(i,j));
            else if(S[i][j] == 'O')
                Xf = i, Yf = j,
                S[i][j] = '.';
            else if(S[i][j] == 'I')
                Xs = i, Ys = j,
                S[i][j] = '.';

    for(;!Q.empty();Q.pop())
        for(int k=1;k<=4;k++)
            if(S[Xn][Yn] == '.' && !B[Xn][Yn])
            {
                B[Xn][Yn] = B[Xn-X[k]][Yn-Y[k]] + 1;
                Q.push(make_pair(Xn,Yn));
                Max = max(Max,B[Xn][Yn]);
            }
}

void Rezolvare(void)
{
    Lee();

    queue<pair<int,int> > Q;

    for(int i=1;i<=N;i++)
        for(int j=1;j<=M;j++)
            Best[i][j] = -1;

    List[B[Xs][Ys]].push_back(make_pair(Xs,Ys));

    for(int i=Max;i>=0;i--)
    {
        for(int j=0;j<List[i].size();j++)
        {
            Best[List[i][j].first][List[i][j].second] = i;
            Q.push(List[i][j]);
        }

        for(;!Q.empty();Q.pop())
            for(int k=1;k<=4;k++)
                if(!inLista[Xn][Yn])
                    if(S[Xn][Yn] == '.' && Best[Xn][Yn] == -1)
                    {
                        if(B[Xn][Yn] >= i)
                        {
                            Best[Xn][Yn] = i;
                            Q.push(make_pair(Xn,Yn));
                        }
                        else
                            List[B[Xn][Yn]].push_back(make_pair(Xn,Yn));

                        inLista[Xn][Yn] = 1;
                    }
    }
}

int main()
{
    citire();
    Rezolvare();

    /*for(int i=1;i<=N;i++)
    {
        for(int j=1;j<=M;j++)
            if(Best[i][j] > -1)
                cout << Best[i][j];
            else
                cout << ".";
        cout << "\n";
    }*/

    g << Best[Xf][Yf];
}