Cod sursa(job #2641100)

Utilizator RaresFelixTudose Rares Felix RaresFelix Data 10 august 2020 07:22:32
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.36 kb
#include <bits/stdc++.h>
#define SSTR( x ) static_cast< std::ostringstream & >( \
        ( std::ostringstream() << std::dec << x ) ).str()
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<pair<int,int> > vii;

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

int D_X[]={1,0,-1,0},D_Y[]={0,1,0,-1};

int DIST[1005][1005],VIZ[1005][1005],xs,ys,xf,yf,rez;
queue<ii> QUE;
int n,m;
char car;

int ok_coord(int x,int y)
{
    return (x>=1&&x<=n&&y>=1&&y<=m);
}

void bfs()
{
    while(!QUE.empty()){
        int x=QUE.front().first,y=QUE.front().second;QUE.pop();
        for(int k=0;k<4;k++){
            int x1=x+D_X[k],y1=y+D_Y[k];
            if(ok_coord(x1,y1) && DIST[x1][y1]==-1){
                DIST[x1][y1]=DIST[x][y]+1;
                QUE.push({x1,y1});
            }
        }
    }
}

int sol_ok(int val)
{
    while(!QUE.empty())QUE.pop();
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            VIZ[i][j]=0;
    VIZ[xs][ys]=1;
    if(DIST[xs][ys]<val)return 0;
    QUE.push({xs,ys});
    while(!QUE.empty()){
        int x=QUE.front().first,y=QUE.front().second;QUE.pop();
        for(int k=0;k<4;k++){
            int x1=x+D_X[k],y1=y+D_Y[k];
            if(ok_coord(x1,y1) && DIST[x1][y1]>=val && !VIZ[x1][y1]){
                if(x1==xf && y1==yf)return 1;
                VIZ[x1][y1]=1;
                QUE.push({x1,y1});
            }
        }
    }
    return 0;
}

void bin()
{
    int st=1,dr=n+m,mij = 0;
    while(st<=dr){
        mij=(st+dr)/2;
        if(sol_ok(mij)){
            rez=mij;
            st=mij+1;
        }
        else dr=mij-1;
    }
}

int main()
{
    ///cin.tie(0);cout.tie(0);ios::sync_with_stdio(0);
    fi>>n>>m;rez=-1;
    for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++){
            fi>>car;
            if(car=='.') DIST[i][j]=-1;
            else if(car=='*') DIST[i][j]=-2;
            else if(car=='D') {
                QUE.push({i,j});
                DIST[i][j]=0;
            }
            else if(car=='I') {
                xs=i;ys=j;
                DIST[i][j]=-1;
            }
            else if(car=='O') {
                xf=i;yf=j;
                DIST[i][j]=-1;
            }
		}
    bfs();
    bin();
    fo<<rez;
    return 0;
}