Cod sursa(job #2118542)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 30 ianuarie 2018 18:56:22
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.62 kb
#include <bits/stdc++.h>
#define Nmax 1005
#define tip pair <int,int>
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
int a[Nmax][Nmax];
bool T[Nmax][Nmax];
int n,m,x_start,x_stop,y_start,y_stop,lo,hi,mid,ans;
int i,j,iu,ju,k;
char s[Nmax];
inline bool valid(const int &x, const int &y)
{
    return x>0 and y>0 and x<=n and y<=m and !a[x][y];
}
inline bool valid2(const int &x, const int &y)
{
    return x>0 and y>0 and x<=n and y<=m and !T[x][y];
}
queue <tip> q;
const int dx[]={0,0,-1,1};
const int dy[]={-1,1,0,0};
bool maybe(const int &x)
{
    if(a[x_start][y_start]<x) return false;
    memset(T,false,sizeof(T));
    q.push({x_start,y_start});
    T[x_start][y_start]=true;
    while(!q.empty())
    {
        i=q.front().first;
        j=q.front().second;
        q.pop();
        for(k=0;k<4;k++)
        {
            iu=i+dx[k];
            ju=j+dy[k];
            if(valid2(iu,ju) and a[iu][ju]>=x)
            {
                T[iu][ju]=true;
                q.push({iu,ju});
            }
        }
    }
    return T[x_stop][y_stop];
}
void BFS()
{
    while(!q.empty())
    {
        i=q.front().first;
        j=q.front().second;
        q.pop();
        for(k=0;k<4;k++)
        {
            iu=i+dx[k];
            ju=j+dy[k];
            if(valid(iu,ju))
            {
                a[iu][ju]=a[i][j]+1;
                q.push({iu,ju});
            }
        }
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    f>>n>>m;
    f.get();
    for(i=1;i<=n;i++)
    {
        f.getline(s,Nmax);
        for(j=0;j<m;j++)
        {
            switch (s[j])
            {
                case 'D':
                    {
                        a[i][j+1]=1;
                        q.push({i,j+1});
                        break;
                    }
                case '*':
                    {
                        a[i][j+1]=-1;
                        break;
                    }
                case 'I':
                    {
                        x_start=i;
                        y_start=j+1;
                        break;
                    }
                case 'O':
                    {
                        x_stop=i;
                        y_stop=j+1;
                        break;
                    }
            }
        }
    }
    BFS();
    lo=0;
    hi=a[x_start][y_start];
    while(lo<=hi)
    {
        mid=(lo+hi)>>1;
        if(maybe(mid))
        {
            ans=mid;
            lo=mid+1;
        }
        else hi=mid-1;
    }
    g<<ans-1;

    return 0;
}