Cod sursa(job #1143849)

Utilizator classiusCobuz Andrei classius Data 16 martie 2014 10:37:55
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.44 kb
using namespace std;

#include<cstdio>
#include<utility>
#include<vector>
#include<queue>

const int MAXN=1100;

bool a[MAXN][MAXN],ax[MAXN][MAXN];
int ds[MAXN][MAXN];

int main(){
    freopen("barbar.in","r",stdin);
    freopen("barbar.out","w",stdout);

    int n,m,stx,sty,sfx,sfy;
    queue<pair<int,int> > q;

    scanf("%d%d",&n,&m);

    for(int i=1;i<=n;i++){
        scanf("%*c");
        for(int j=1;j<=m;j++){
            ds[i][j]=9999;
            char ch;
            scanf("%c",&ch);
            if(ch=='I'){
                stx=i;
                sty=j;
            }
            if(ch=='O'){
                sfx=i;
                sfy=j;
            }
            if(ch=='D'){
                ds[i][j]=0;
                q.push(make_pair(i,j));
            }
            if(ch=='*'){
                a[i][j]=true;
            }
        }
    }

    int ve[4][2]={{0,1},{0,-1},{1,0},{-1,0}};

    #define vi i+ve[t][0]
    #define vj j+ve[t][1]

    while(!q.empty()){
        int i=q.front().first;
        int j=q.front().second;
        q.pop();

        for(int t=0;t<4;t++){
            if(vi>0 && vj>0 && vi<=n && vj<=m && ds[vi][vj]>ds[i][j]+1 && !a[vi][vj]){
                ds[vi][vj]=ds[i][j]+1;
                q.push(make_pair(vi,vj));
            }
        }
    }

    ax[stx][sty]=true;
    q.push(make_pair(stx,sty));

    while(!q.empty()){
        int i=q.front().first;
        int j=q.front().second;
        q.pop();

        for(int t=0;t<4;t++){
            if(vi>0 && vj>0 && vi<=n && vj<=m && !a[vi][vj] && !ax[vi][vj]){
                ax[vi][vj]=1;
                q.push(make_pair(vi,vj));
            }
        }
    }

    if(!ax[sfx][sfy]){
        printf("-1");
        return 0;
    }

    int hi=3000,lo=0;

    while(lo<hi){
        int mid=(lo+hi)/2;

        bool ok[MAXN][MAXN]={};

        if(mid>=ds[stx][sty]){
            hi=mid;
            continue;
        }

        ok[stx][sty]=true;

        q.push(make_pair(stx,sty));

        while(!q.empty()){
            int i=q.front().first;
            int j=q.front().second;
            q.pop();

            for(int t=0;t<4;t++){
                if(vi>0 && vj>0 && vi<=n && vj<=m && !a[vi][vj] && mid<ds[vi][vj] && !ok[vi][vj]){
                    ok[vi][vj]=true;
                    q.push(make_pair(vi,vj));
                }
            }
        }
        if(ok[sfx][sfy]){
            lo=mid+1;
        }else{
            hi=mid;
        }
    }

    printf("%d",lo);

    return 0;
}