Cod sursa(job #2361051)

Utilizator Raresr14Rosca Rares Raresr14 Data 2 martie 2019 12:34:42
Problema Barbar Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.43 kb
#include <fstream>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n,m,ok,i,j,p,u,c[2][1001*1001],ist,jst,fini,finj,a[1001][1001],b[1001][1001],f[1001][1001],st,dr,mid;
char ch;
int di[]={0,0,-1,1};
int dj[]={-1,1,0,0};
int main (){
    fin>>n>>m;
    for(i=1;i<=n;i++)
        for(j=1;j<=m;j++){
            fin>>ch;
            if(ch=='.')
                a[i][j]=b[i][j]=0;
            if(ch=='*'){
                a[i][j]=0;
                b[i][j]=-1;
            }
            if(ch=='D'){
                a[i][j]=1;
                b[i][j]=-2;
                u++;
                c[0][u]=i;
                c[1][u]=j;
            }
            if(ch=='I'){
                a[i][j]=0;
                ist=i;
                jst=j;
            }
            if(ch=='O'){
                a[i][j]=0;
                fini=i;
                finj=j;
            }
        }
    p=1;
    while(p<=u){
        int ic=c[0][p];
        int jc=c[1][p];
        for(int d=0;d<4;d++){
            int iv=ic+di[d];
            int jv=jc+dj[d];
            if(iv>=1&&iv<=n&&jv>=1&&jv<=m&&a[iv][jv]==0){
                a[iv][jv]=1+a[ic][jc];
                u++;
                c[0][u]=iv;
                c[1][u]=jv;
            }
        }
        p++;
    }
    for(i=1;i<=n;i++)
        for(j=1;j<=m;j++)
            if(b[i][j]!=-1&&b[i][j]!=-2)
                b[i][j]=a[i][j];

    st=1;
    dr=1001*1001;

    while(st<=dr){
        mid=(st+dr)/2;
        p=u=1;
        for(i=1;i<=n;i++)
            for(j=1;j<=m;j++)
                f[i][j]=0;
        c[0][p]=ist;
        c[1][p]=jst;
        f[ist][jst]=1;
        while(p<=u){
            int ic=c[0][p];
            int jc=c[1][p];
            for(int d=0;d<4;d++){
                int iv=ic+di[d];
                int jv=jc+dj[d];
                if(iv>=1&&iv<=n&&jv>=1&&jv<=m&&b[iv][jv]>=mid&&f[iv][jv]==0){
                    f[iv][jv]=1;
                    u++;
                    c[0][u]=iv;
                    c[1][u]=jv;
                }
            }
            p++;
        }

        if(f[fini][finj]==0)
            dr=mid-1;
        else
            st=mid+1;
    }
    if(dr-1==-1)
        fout<<dr-1;
    else{
        if(b[ist+1][jst]==-2||b[ist-1][jst]==-2||b[ist][jst+1]==-2||b[ist][jst-1]==-2)
            fout<<1;
        else
            fout<<dr-1;
    }
    return 0;
}