Cod sursa(job #829331)

Utilizator enedumitruene dumitru enedumitru Data 5 decembrie 2012 01:38:17
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.11 kb
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
struct nod {int x,y;} start,stop;
int n,m,a[1005][1005],d[1005][1005];
int viz[1005][1005];
queue <nod> q;
int dx[]={0,1,0,-1};
int dy[]={-1,0,1,0};
bool ok(int p)
{   if(d[start.x][start.y]==-2) return 1;
    if(d[start.x][start.y]<p) return 0;
    q.push(start);
    memset(viz,0,sizeof(viz));
    viz[start.x][start.y]=1;
    while(!q.empty())
    {  nod temp=q.front();
        for(int i=0;i<4;i++)
        {   temp.x+=dx[i];
            temp.y+=dy[i];
            if(d[temp.x][temp.y]>=p && viz[temp.x][temp.y]==0)
            {viz[temp.x][temp.y]=1;
             q.push(temp);
            }
            temp.x-=dx[i];
            temp.y-=dy[i];
        }
        q.pop();
    }
    return viz[stop.x][stop.y];
}
int main()
{   freopen("barbar.in","r",stdin);
    freopen("barbar.out","w",stdout);
    int n,m,i,j;char ch;
    scanf("%d %d\n",&n,&m);
    for(i=1;i<=n;i++)
     for(j=1;j<=m;j++)
        d[i][j]=-2;
    for(i=0;i<=n+1;i++) d[i][0]=d[i][m+1]=-1;
    for(i=0;i<=m+1;i++) d[0][i]=d[n+1][i]=-1;
    nod temp,nou;
    for(i=1;i<=n;i++,scanf("%c",&ch))
    for(j=1;j<=m;j++)
        {   scanf("%c",&ch);
            if(ch=='*') d[i][j]=-1;
                else if(ch=='.');
                        else if(ch=='D') {d[i][j]=0; nou.x=i; nou.y=j; q.push(nou); }
                                else if(ch=='O') {stop.x=i;stop.y=j;}
                                        else {start.x=i;start.y=j;}
        }
    // Lee plecand de la dragoni
    while(!q.empty())
    {   temp=q.front(); q.pop();
        for(int lin,col,k=0; k<4; ++k)
            {lin =temp.x+dx[k]; col =temp.y+dy[k];
             if(d[lin][col]==-2)
                {d[lin][col]=d[temp.x][temp.y]+1; nou.x=lin; nou.y=col; q.push(nou);}
            }
    }
    // Cautare binara
    int st,dr,med,last;
    st=0;dr=n*m;last=-1;
    while(st<=dr)
        {   med=(st+dr)/2;
            if(ok(med)) {last=med; st=med+1;         }
                else dr=med-1;
        }
    printf("%d\n",last); return 0;
}