Cod sursa(job #1345675)

Utilizator HDT_TibiHudema Dumitru Tiberiu HDT_Tibi Data 17 februarie 2015 19:54:44
Problema Kdrum Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.54 kb
#include <fstream>
#include <queue>
using namespace std;
 
ifstream fin("kdrum.in");
ofstream fout("kdrum.out");
 
struct Nod{int x,y,div,pas;};
 
queue<Nod> lista;
int n,m,k,xi,yi,xf,yf,a[53][53],q,v[6000],v2[12001];
short dx[]={-1,0,1,0},dy[]={0,1,0,-1},pas=1;
bool b[53][53][6000];
 
void citire()
{
    fin>>n>>m>>k;
    fin>>xi>>yi>>xf>>yf;
    for(int i=1; i<=n; i++)
        for (int j=1; j<=m; j++)
            fin>>a[i][j];
}

void extract(int x)
{
	q++;v[q]=1;v2[1]=q;
	for(int i=2; i<=x/2; i++)
		if(x%i==0){q++;v[i]=q;v2[q]=i;}
		q++;v[x]=q;v2[q]=x;
}		

short cmmdc(long long a, short b)
{
   long long c;
    while (b) {
        c = a % b;
        a = b;
        b = c;
    }
    return a;
}
 
void add(int x,int y, int div, int pas)
{
    Nod t;
    t.x=x;
    t.y=y;
    t.pas=pas;
    t.div=div;
    lista.push(t);
    b[x][y][div]=1;
}
 
void rezolvare()
{
    add(xi ,yi ,v[cmmdc(a[xi][yi],k)] ,1 );
 
    while ( !lista.empty() )
    {
        Nod t=lista.front();
        lista.pop();
 
        for(int i=0; i<=3; i++)
        {
            int nx=t.x+dx[i];
            int ny=t.y+dy[i];
 
            if(a[nx][ny]!= 0){
                int d= cmmdc(v2[t.div] * a[nx][ny] ,k );
                if(b[nx][ny][v[d]]!=1){
                    if(nx==xf and ny==yf and d==k) {fout<<t.pas+1<<endl; return;}
                    add(nx,ny,v[d],t.pas+1);
                }
            }
        }
    }
}
 
int main()
{
    citire();
    extract(k);
    rezolvare();
    return 0;
}