Cod sursa(job #2971487)

Utilizator IeremiaNicolaescu Ieremia Ieremia Data 27 ianuarie 2023 14:27:14
Problema Barbar Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.14 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n,m,d[1001][1001],dx[]= {-1,0,1,0},dy[]= {0,1,0,-1},xi,xf,yi,yf,st,dr,i,j;
short int mat[1001][1001];
bool viz[1001][1001];
struct punct
{
    int l;
    int c;
};
queue<punct>q;
char ch;
int lee(int k)
{
    memset(viz,0,sizeof(viz));
    if(d[xi][yi]>k)
    {
        q.push({xi,yi});
        viz[xi][yi]=1;
    }
    else
    {
        return 0;
    }
    while(!q.empty())
    {
        int l=q.front().l;
        int c=q.front().c;
        q.pop();
        for(i=0; i<4; i++)
        {
            int lv=l+dx[i];
            int cv=c+dy[i];
            if(lv>=1&&lv<=n&&cv>=1&&cv<=m&&mat[lv][cv]==0&&viz[lv][cv]==0&&d[lv][cv]>k)
            {
                viz[lv][cv]=1;
                q.push({lv,cv});
            }
        }
    }
    return viz[xf][yf];
}
int main()
{
    fin>>n>>m;
    for(i=1; i<=n; i++)
    {
        for(j=1; j<=m; j++)
        {
            fin>>ch;
            if(ch=='D')
            {
                mat[i][j]=2;
                q.push({i,j});
                d[i][j]=1;
            }
            else if(ch=='*')
                mat[i][j]=1;
            else if(ch=='I')
            {
                xi=i;
                yi=j;
            }
            else if(ch=='O')
            {
                xf=i;
                yf=j;
            }
        }
    }
    while(!q.empty())
    {
        int l=q.front().l;
        int c=q.front().c;
        q.pop();
        for(i=0; i<4; i++)
        {
            int lv=l+dx[i];
            int cv=c+dy[i];
            if(lv>=1&&lv<=n&&cv>=1&&cv<=m&&mat[lv][cv]==0&&d[lv][cv]==0)
                d[lv][cv]=d[l][c]+1;
            q.push({lv,cv});
        }
    }
    int st=0,dr=n*m,sol=-1;
    while(st<=dr)
    {
        int mid=(st+dr)/2;
        int ok=lee(mid);
        if(ok==1)
        {
            sol=mid;
            st=mid+1;
        }
        else
        {
            dr=mid-1;
        }
    }
    cout<<sol;
    return 0;
}