Cod sursa(job #6411)

Utilizator devilkindSavin Tiberiu devilkind Data 19 ianuarie 2007 14:12:56
Problema Barbar Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.56 kb
#include <stdio.h>
#define NMAX 1024

FILE *f = fopen("barbar.in","rt"), *g = fopen("barbar.out","wt");


long int n,m,i,j,k,a[NMAX][NMAX],cost[NMAX][NMAX],hash[NMAX][NMAX];
long int cd[NMAX*NMAX*2][2],dr,start[2],fin[2],st,nr;


void citire()
{char D[2048];
fscanf(f,"%ld %ld",&n,&m);

for (i=0;i<=n+1;i++)
    {hash[i][m+1]=1;
    hash[i][0]=1;}

for (i=0;i<=m+1;i++)
    {hash[n+1][i]=1;
    hash[0][i]=1;}


char c;
c=fgetc(f);
st=1;
dr=0;
for (i=1;i<=n;i++)
    {
    fgets(D,2024,f);
    for (j=1;j<=m;j++)
        {if (D[j-1]=='.') a[i][j]=0;
        if (D[j-1]=='*') {a[i][j]=1;nr++;}
	if (D[j-1]=='D') {cd[++dr][0]=i;cd[dr][1]=j;hash[i][j]=1;a[i][j]=0;}
	if (D[j-1]=='I') {start[0]=i;start[1]=j;a[i][j]=0;}
	if (D[j-1]=='O') {fin[0]=i;fin[1]=j;a[i][j]=0;}
        }
    }
}

int BF(long int c)
{long int i,final,x,y;
final=dr;
for (i=st;i<=dr;i++)
    {cost[cd[i][0]][cd[i][1]]=c;
    x=cd[i][0];y=cd[i][1];
    if (!hash[x-1][y]&&(!a[x-1][y]))
	{cd[++final][0]=x-1;cd[final][1]=y;hash[x-1][y]=1;}
    if (!hash[x][y-1]&&(!a[x][y-1]))
	{cd[++final][0]=x;cd[final][1]=y-1;hash[x][y-1]=1;}
    if (!hash[x+1][y]&&(!a[x+1][y]))
	{cd[++final][0]=x+1;cd[final][1]=y;hash[x+1][y]=1;}
    if (!hash[x][y+1]&&(!a[x][y+1]))
	{cd[++final][0]=x;cd[final][1]=y+1;hash[x][y+1]=1;}
    }
if (final==dr) return 0;
st=dr+1;
dr=final;
return 1;
}
    



long int MIN(long int a, long int b)
{
if (a>b) return b;
return a;
}
    
   
int drum(long int cst)
{
long int st,dr,final,i,x,y;
for (i=1;i<=n;i++)
    for (j=1;j<=m;j++)
	hash[i][j]=0;
st=1;dr=1;
cd[1][0]=start[0];
cd[1][1]=start[1];
while (st<=dr)
      {
      final=dr;
      for (i=st;i<=dr;i++)
          {x=cd[i][0];y=cd[i][1];
	  if (!hash[x-1][y]&&(!a[x-1][y])&&(cost[x-1][y]>=cst)) {cd[++final][0]=x-1;cd[final][1]=y;hash[x-1][y]=1;}
	  if (!hash[x][y-1]&&(!a[x][y-1])&&(cost[x][y-1]>=cst)) {cd[++final][0]=x;cd[final][1]=y-1;hash[x][y-1]=1;}
	  if (!hash[x+1][y]&&(!a[x+1][y])&&(cost[x+1][y]>=cst)) {cd[++final][0]=x+1;cd[final][1]=y;hash[x+1][y]=1;}
	  if (!hash[x][y+1]&&(!a[x][y+1])&&(cost[x][y+1]>=cst)) {cd[++final][0]=x;cd[final][1]=y+1;hash[x][y+1]=1;}
	  }
      st=dr+1;dr=final;
      }
if (hash[fin[0]][fin[1]]) return 1;
return 0;
}


void solve()
{long int ok,st,dr,mid;
ok=1;
st=1;
i=1;
while (ok)
    {ok=BF(i-1);
    i++;}


st=1;dr=n*m;
while (st<dr)
      {mid=(st+dr)/2;
      if (drum(mid)) st=mid+1;
	 else dr=mid;
      }
fprintf(g,"%ld",dr);

}


int main()
{
citire();
solve();
fclose(f);
fclose(g);
return 0;
}