Cod sursa(job #2676726)

Utilizator VladNANegoita Vlad-Andrei VladNA Data 24 noiembrie 2020 21:02:25
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.29 kb
#include <bits/stdc++.h>
#define NMAX 1003
#define  x first
#define y second
using namespace std;

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

int n,m;
int a[NMAX][NMAX],b[NMAX][NMAX];
const int di[4]={0,0,1,-1};
const int dj[4]={1,-1,0,0};
queue< pair <int, int> >q;
pair<int, int> aux;
pair<int, int> in,out;

inline bool verif( pair<int, int> bla)
{
    return (bla.x<=n && bla.x>=1 && bla.y<=m && bla.y>=1);
}

void bfs1()
{
    while(!q.empty())
    {
        pair<int,int> u;
        u=q.front();
        q.pop();
        for(int k=0;k<4;k++)
        {
            pair<int, int>v;
            v.x=u.x+di[k];
            v.y=u.y+dj[k];
            if(verif(v) && a[v.x][v.y]>a[u.x][u.y]+1)
            {
                a[v.x][v.y]=a[u.x][u.y]+1;
                q.push(v);
            }
        }
    }
}

bool bfs2(int dmin)
{
    memset(b,0,sizeof(b));
    q.push(in);
    b[in.x][in.y]=1;
    while(!q.empty())
    {
        pair<int, int>u;
        u=q.front();
        q.pop();
        for(int k=0;k<4;k++)
        {
            pair<int, int>v;
            v.x=u.x+di[k];
            v.y=u.y+dj[k];
            if(verif(v) && b[v.x][v.y]==0 && a[v.x][v.y]>=dmin)
            {
                b[v.x][v.y]=b[u.x][u.y]+1;
                q.push(v);
            }
        }
    }
    if(b[out.x][out.y])
        return true;
    else
        return false;
}

int main()
{
    fin>>n>>m;
    char x;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        {
            fin>>x;
            a[i][j]=1e9;
            if(x=='D')
            {
                aux.x=i;
                aux.y=j;
                a[i][j]=0;
                q.push(aux);
            }
            else if(x=='I')
            {
                in.x=i;
                in.y=j;
            }
            else if(x=='O')
            {
                out.x=i;
                out.y=j;
            }
            else if(x=='*')
                a[i][j]=-1;
        }
    bfs1();
    int st=1,dr=a[in.x][in.y],mij,best=-1;
    while(st<=dr)
    {
        mij=(st+dr)/2;
        if(bfs2(mij))
        {
            best=mij;
            st=mij+1;
        }
        else
            dr=mij-1;
    }
    fout<<best;
    return 0;
}