Cod sursa(job #348222)

Utilizator Alexa_ioana_14Antoche Ioana Alexandra Alexa_ioana_14 Data 14 septembrie 2009 21:55:58
Problema Kdrum Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.49 kb
#include<cstdio>
#define N 51
#define G 18
bool viz[N][N];
int a[N][N],pas,sum=250000000,d[N][N],pr=1;
short int n,m,k,x1,x2,y1,y2,x3,y3;
const int dx[]={0,0,1,-1};
const int dy[]={-1,1,0,0};
short int coada[N*N][2],x[2],y[2];
int u,p;
void bfs(short int x1,short int y1,int pas)
{
	u=p=0;
	coada[u][0]=x1;
	coada[u++][1]=y1;
	d[x1][y1]=1;
	while (u!=p)
	{
		x[0]=coada[p][0];
		x[1]=coada[p++][1];
		for (int i=0; i<4; ++i)
		{
			y[0]=dx[i]+x[0];
			y[1]=dy[i]+x[1];
			if (y[0]&&y[0]<=n&&y[1]&&y[1]<=m&&a[y[0]][y[1]])
			if (!d[y[0]][y[1]])
			{
				coada[u][0]=y[0];
				coada[u++][1]=y[1];
				d[y[0]][y[1]]=1+d[x[0]][x[1]];
			}
		}
	}
	if (pas+d[x2][y2]-1<sum)
		sum=pas+d[x2][y2]-1;
	for (int i=1;i<=n; ++i)
		for (int j=1; j<=m; ++j)
			d[i][j]=0;
}
void dfs(short int x1,short int y1)
{
	++pas;
	pr*=a[x1][y1];
	if (pr%k==0)
	{
		bfs(x1,y1,pas);
		return;
	}
	viz[x1][y1]=true;
	for (short int i=0; i<4; ++i)
	{
		x3=dx[i]+x1;
		y3=dy[i]+y1;
		if (x3&&x3<=n&&y3&&y3<=m&&a[x3][y3]&&!viz[x3][y3])
		{
			dfs(x3,y3);
			if (x3&&x3<=n&&y3&&y3<=m&&a[x3][y3]&&!viz[x3][y3])
			{
			--pas;
			pr/=a[x3][y3];
			}
		}
	}
}
void citire()
{
	freopen("kdrum.in","r",stdin);
	freopen("kdrum.out","w",stdout);
	scanf("%hd%hd%hd%hd%hd%hd%hd",&n,&m,&k,&x1,&y1,&x2,&y2);
	//desc(k);
	pr=1;
	pas=0;
	for (int i=1; i<=n; ++i)
		for (int j=1; j<=m; ++j)
			scanf("%d",&a[i][j]);
	dfs(x1,y1);
}
int main()
{
	citire();
	printf("%d",sum);
	return 0;
}