Cod sursa(job #2303331)

Utilizator FrostfireMagirescu Tudor Frostfire Data 16 decembrie 2018 00:11:47
Problema Barbar Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.31 kb
#include <fstream>
#include <queue>
#include <cstring>

using namespace std;

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

int n,m,dx[4]={-1,0,1,0},
        dy[4]={0,-1,0,1},d[1003][1003], st = 1050, dr;

char s[1003][1003];

struct element{
   int x,y;
}inceput,sfarsit;
bool b[1003][1003];

queue<element> stiva;

bool corect(int mij)
{
    memset(b,0,sizeof(b));
    b[inceput.x][inceput.y] = 1;
    stiva.push(inceput);
    while(!stiva.empty()){
        element a;
        a = stiva.front();
        stiva.pop();
        for(int t=0; t<4; t++){
            int ivec = a.x + dx[t];
            int jvec = a.y + dy[t];
            if(s[ivec][jvec] != '*' && s[ivec][jvec] != 'D' && d[ivec][jvec] >= mij
               && ivec>=1 && ivec<=n && jvec>=1 && jvec<=m && b[ivec][jvec] == 0){
                b[ivec][jvec] = 1;
                element c;
                c.x = ivec;
                c.y = jvec;
                stiva.push(c);
            }
        }
    }
    if(b[sfarsit.x][sfarsit.y]) return 1;
    return 0;
}

int main()
{
    f >> n >> m;
    for(int i=1; i<=n; i++)

      for(int j=1; j<=m;j++) {
              f >> s[i][j];
              if(s[i][j]=='D') {
                element a;
                a.x = i;
                a.y = j;
                stiva.push(a);
              }
               else if(s[i][j]=='I') inceput.x = i, inceput.y = j;
                 else if(s[i][j]=='O') sfarsit.x = i, sfarsit.y = j;
    }

    while(!stiva.empty()){
        element a;
        a = stiva.front();
        stiva.pop();

        for(int t=0;t<4;t++){
            int ivec = a.x+dx[t];
            int jvec = a.y+dy[t];
            if(s[ivec][jvec]!='D' && (d[ivec][jvec]==0 || d[ivec][jvec]>d[a.x][a.y]+1)
                && (ivec>=1 && ivec<=n && jvec>=1 && jvec<=m))
            {
               d[ivec][jvec] = d[a.x][a.y]+1;
               dr = max(dr, d[ivec][jvec]);
               st = min(st, d[ivec][jvec]);
               element b;
               b.x = ivec;
               b.y = jvec;
               stiva.push(b);
            }
        }
    }

    int rez = -1;
    while(st < dr){
        int mij = (st + dr) / 2;
        if(corect(mij)) st = mij + 1, rez = mij;
          else dr = mij-1;
    }
    g << rez << '\n';
    return 0;
}