Cod sursa(job #3180734)

Utilizator Sasha_12454Sasha Costea Sasha_12454 Data 5 decembrie 2023 20:34:52
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.32 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in ("barbar.in");
ofstream out ("barbar.out");
queue <pair<int,int>> q;
const int NMAX=1005;
int n,m;
int ys,xs,xf,yf;
int dx[]= {1,0,-1,0},dy[]= {0,1,0,-1};
char ch[NMAX];
int a[NMAX][NMAX],leel[NMAX][NMAX];
bool inbound(int i, int j)
{
    return i>=1 && j>=1 && i<=n && j<=m;
}
void lee()
{
    while(!q.empty())
    {
        int x=q.front().first;
        int y=q.front().second;
        q.pop();
        for(int i=0; i<4; i++)
        {
            int l=x+dx[i];
            int c=y+dy[i];
            if(inbound(l,c) && a[l][c]!=-2 && (a[l][c]==-1 || a[l][c]>a[x][y]+1))
            {
                q.push(make_pair(l,c));
                a[l][c]=a[x][y]+1;
            }
        }
    }
}
bool check(int minim)
{
    if(a[xs][ys]<minim)
        return false;
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            leel[i][j]=0;
    queue <pair<int,int>> q;
    q.push(make_pair(xs,ys));
    leel[xs][ys]=1;
    while(!q.empty())
    {
        int x=q.front().first;
        int y=q.front().second;
        q.pop();
        for(int i=0; i<4; i++)
        {
            int l=x+dx[i];
            int c=y+dy[i];
            if(inbound(l,c) && a[l][c]>=minim && leel[l][c]==0)
                leel[l][c]=leel[x][y]+1,q.push(make_pair(l,c));
        }
    }
    if(leel[xf][yf])
        return true;
    return false;
}
int cautarebinara()
{
    int st=1,dr=100000,res;
    while(st<=dr)
    {
        int mij=(st+dr)/2;
        if(check(mij))
        {
	    st=mij+1;
res=mij; 
        }
        else
            dr=mij-1;
    }
    return res;
}
int main()
{

    in>>n>>m;
    for(int i=1; i<=n; i++)
    {
        in>>ch;
        for(int j=0; j<strlen(ch); j++)
        {
            if(ch[j]=='.')
                a[i][j+1]=-1;
            else if(ch[j]=='*')
                a[i][j+1]=-2;
            else if(ch[j]=='I')
            {
 a[i][j+1]=-1;
                xs=i,ys=j+1;
            }
            else if(ch[j]=='O')
            {
 a[i][j+1]=-1;
                xf=i,yf=j+1;
            }
            else
            {
                a[i][j+1]=0;
                q.push(make_pair(i,j+1));
            }
        }
    }
    lee();
    out<<cautarebinara();
    return 0;
}