Cod sursa(job #414693)

Utilizator DeadEyeNaiba Mihai Lucian DeadEye Data 10 martie 2010 13:15:30
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.03 kb
#include<cstdio>
int sf,xz,m,n,ps1,ps2,pf1,pf2,px[1002][1002],p[1002][1002],dl[1002],dc[1002];
char a[1002][1002];
struct point
{
	int lz,cz;
};
point cc[1<<20];
int max(int x,int y)
{
	if(x>y)
		return x;
	return y;
}
int l1()
{
	int i,j,nr=0;
	point x,y;
	for(i=1;i<=m;i++)
		for(j=1;j<=n;j++)
			if(a[i][j]=='D')
			{
				cc[nr].lz=i;
				cc[nr].cz=j;
				nr++;
			}
	for(i=0;i<nr;i++)
	{
		x.lz=cc[i].lz;
		x.cz=cc[i].cz;
		for(j=0;j<4;j++)
			if(p[x.lz+dl[j]][x.cz+dc[j]]==0 && a[x.lz+dl[j]][x.cz+dc[j]]!='*' && a[x.lz+dl[j]][x.cz+dc[j]]!='D')
			{
				y.lz=x.lz+dl[j];
				y.cz=x.cz+dc[j];
				p[y.lz][y.cz]=p[x.lz][x.cz]+1;
				cc[nr]=y;
				nr++;
			}
	}
	return 0;
}
bool l2(int nub)
{
	int i,j,nr=0;
	point x,y;
	cc[nr].lz=ps1;
	cc[nr].cz=ps2;
	nr++;
	if(p[ps1][ps2]<nub)
		return 0;
	for(i=1;i<=m;i++)
		for(j=1;j<=n;j++)
			px[i][j]=0;
	px[ps1][ps2]=1;
	for(i=0;i<nr;i++)
	{
		x.lz=cc[i].lz;
		x.cz=cc[i].cz;
		for(j=0;j<4;j++)
		{
			y.lz=x.lz+dl[j];
			y.cz=x.cz+dc[j];
			if(px[y.lz][y.cz]==0 && a[y.lz][y.cz]!='*' && a[y.lz][y.cz]!='D' && p[y.lz][y.cz]>=nub)
			{
				px[y.lz][y.cz]=1;
				cc[nr]=y;
				nr++;
			}
		}
	}
	if(px[pf1][pf2]==0)
	{
		return 0;
	}
	return 1;
}
int cb()
{
	int i=0,pas=1<<12;
	for(i=0;pas;pas>>=1)
		if(l2(i+pas))
			i+=pas;
	return i;
}
int main()
{
	int i,j,nn;
	freopen("barbar.in","r",stdin);
	freopen("barbar.out","w",stdout);
	dl[0]=1;
	dl[1]=0;
	dl[2]=-1;
	dl[3]=0;
	dc[0]=0;
	dc[1]=1;
	dc[2]=0;
	dc[3]=-1;
	scanf("%d%d\n",&m,&n);
	for(i=1;i<=m;i++)
		gets(a[i]+1);
	for(i=0;i<=m+1;i++)
	{
		a[i][0]='*';
		a[i][n+1]='*';
	}
	for(j=0;j<=n+1;j++)
	{
		a[0][j]='*';
		a[m+1][j]='*';
	}
	for(i=1;i<=m;i++)
		for(j=1;j<=n;j++)
			if(a[i][j]=='O')
			{
				pf1=i;
				pf2=j;
			}
			else if(a[i][j]=='I')
			{
				ps1=i;
				ps2=j;
			}
	l1();
	sf=max(m,n);
	xz=cb();
	//OW, pai atunci e mult mai urat ca tre sa tot umblu in PX
	if(xz!=0)
		printf("%d\n",xz);
	else printf("-1\n");
	return 0;
}