Cod sursa(job #2784425)

Utilizator biancalautaruBianca Lautaru biancalautaru Data 16 octombrie 2021 14:16:10
Problema Barbar Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.09 kb
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n,m,i,j,x1,y1,x2,y2,p,u,ic,jc,d,st,dr,mid,sol,a[1001][1001],di[]={-1,0,0,1},dj[]={0,-1,1,0};
bool viz[1001][1001];
char c;

struct punct{
    int x,y;
}q[1000001];

bool inauntru(int i,int j) {
    return i>=1 && i<=n && j>=1 && j<=m;
}

int main() {
    fin>>n>>m;
    p=1;
    u=0;
    for (i=1;i<=n;i++)
        for (j=1;j<=m;j++) {
            fin>>c;
            if (c=='*')
                a[i][j]=-1;
            else
                if (c=='D') {
                    q[++u]={i,j};
                    a[i][j]=1;
                }
                else
                    if (c=='I') {
                        x1=i;
                        y1=j;
                    }
                    else
                        if (c=='O') {
                            x2=i;
                            y2=j;
                        }
        }
    while (p<=u) {
        i=q[p].x;
        j=q[p].y;
        p++;
        for (d=0;d<4;d++) {
            ic=i+di[d];
            jc=j+dj[d];
            if (inauntru(ic,jc) && a[ic][jc]==0) {
                q[++u]={ic,jc};
                a[ic][jc]=a[i][j]+1;
            }
        }
    }
    st=1;
    dr=n*m;
    sol=-1;
    while (st<=dr) {
        mid=(st+dr)/2;
        if (a[x1][y1]<mid) {
            dr=mid-1;
            continue;
        }
        memset(viz,0,sizeof(viz));
        p=u=1;
        q[p]={x1,y1};
        viz[x1][y1]=1;
        while (p<=u && viz[x2][y2]==0) {
            i=q[p].x;
            j=q[p].y;
            p++;
            for (d=0;d<4;d++) {
                ic=i+di[d];
                jc=j+dj[d];
                if (inauntru(ic,jc) && a[ic][jc]>=mid && viz[ic][jc]==0) {
                    q[++u]={ic,jc};
                    viz[ic][jc]=1;
                }
            }
        }
        if (viz[x2][y2]==1) {
            st=mid+1;
            sol=mid-1;
        }
        else
            dr=mid-1;
    }
    fout<<sol;
    return 0;
}