Cod sursa(job #590481)

Utilizator vendettaSalajan Razvan vendetta Data 17 mai 2011 20:07:54
Problema Kdrum Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.72 kb
#include <cstdio>
#define infile "kdrum.in"
#define outfile "kdrum.out"
#define nmax 51
#define nrmax 13
const int ii[]={-1,0,1,0};
const int jj[]={0,1,0,-1};
struct coada
{
    char i,j;
    short int conf;
} co[nmax*nmax*(1<<nrmax)];
short int dp[nmax][nmax][1<<nrmax];
int h[nmax][nmax], d[nrmax], n, m, k, xx1, xx2, yy1, yy2, nr;

int conf( int x , int y )
{
    int conf=0,i;
    for(i=1;d[i]<=x && i<=nr;i++)
        if (((y>>(i-1))&1)==0 && x%d[i]==0)
            conf += (1<<(i-1)), x/=d[i];
    return conf;
}

void read()
{
    int i,j;
    scanf("%d %d %d\n", &n, &m, &k);
    scanf("%d %d %d %d\n", &xx1, &yy1, &xx2, &yy2);
    for (i=1;i<=n;i++)
        for (j=1;j<=m;j++)
            scanf("%d",&h[i][j]);
}

void init()
{
    int i ;
    for (i=2;i<=k;i++)
        while (k%i==0) d[++nr]=i, k/=i;
}

void solve()
{
    int st, dr, t, k, i, j;
    int x, y, z;
    st=dr=1, co[1].i=xx1, co[1].j=yy1, co[1].conf=conf(h[xx1][yy1],0);
    dp[xx1][yy1][co[1].conf]=1;
    while (st<=dr) {
        i=co[st].i;
        j=co[st].j;
        k=co[st].conf;
        for (t=0;t<4;t++){
            x=i+ii[t];
            y=j+jj[t];
            if (x>0 && x<=n && y>0 && y<=m && h[i][j]){
                z=k|conf(h[x][y],k);
                if(!dp[x][y][z]){
                    dp[x][y][z]=dp[i][j][k] + 1;
                    ++dr, co[dr].i=x, co[dr].j=y, co[dr].conf=z;
                    if (x==xx2 && y==yy2 && z+1==(1<<nr)) return;
                }
            }
        }
        ++st;
    }
}


int main()
{
    freopen(infile,"r",stdin);
    freopen(outfile,"w",stdout);

    read();
    init();
    solve();
    printf("%d",dp[xx2][yy2][(1<<nr)-1]);

    return 0 ;
}