Cod sursa(job #1460723)

Utilizator cristian.caldareaCaldarea Cristian Daniel cristian.caldarea Data 13 iulie 2015 17:54:59
Problema Kdrum Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.08 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream fin("kdrum.in");
ofstream fout("kdrum.out");

const int Dim = 52, MaxK = 12001, Inf = 0x3f3f3f3f;
const int dx[] = { 0, 1, 0, -1};
const int dy[] = { 1, 0, -1, 0};

struct Tri {
public:
    Tri(int _x, int _y, int _z) : x(_x), y(_y), z(_z)
    {}
    int x, y, z;

};


queue<Tri> Q;
int n, m, k;
int x1, x2, y1, y2;
int a[Dim][Dim];
int b[Dim][Dim][MaxK];


void Read();
int Cmmdc(int a, int b);
void Bfs();
bool Ok(int x, int y);

int main()
{
    Read();
    Bfs();
  //  fout << b[x2][y2][k];
//    for (int i = 0; i <= k; i++)
//        fout  << b[x2][y2][i];
    fout << b[x2][y2][k];
    return 0;
}

void Read()
{
    fin >> n >> m >>  k;
    fin >> x1 >> y1 >> x2 >> y2;
    for ( int i = 1; i <= n; i++ )
        for ( int j = 1; j <= m; j++ )
            fin >> a[i][j];
}

int Cmmdc(int a, int b)
{
    int c;
    while (b)
    {
        c = b;
        b = a % b;
        a = c;
    }
    return a;
}

bool Ok(int x, int y)
{
    if ( x > n || y > m || x < 1 || y < 1 || a[x][y] == 0 )
        return false;
    return true;
}

void Bfs()
{
    int x, y, xi, yi, val, vali;
    Tri t = Tri(0, 0, 0);
    for ( int i = 1; i <= n; i++ )
        for ( int j = 1; j <= m; j++ )
            for ( int z = 0; z <= k; z++ )
                b[i][j][z] = Inf;
    b[x1][y1][a[x1][y1]] = 1;
    Q.push(Tri(x1, y1, Cmmdc(k, a[x1][y1])));
    while ( !Q.empty() )
    {

        t = Q.front();
        Q.pop();
        x = t.x;
        y = t.y;
        val = t.z;
        //fout << x << ' '  << y << ' ' << val <<  ' ' << b[x][y][val] << '\n';
        for ( int i = 0; i < 4; i++ )
        {


            xi = x + dx[i];
            yi = y + dy[i];
            vali  = Cmmdc(k, val * a[xi][yi]);

            if ( Ok(xi, yi) && b[x][y][val] + 1 < b[xi][yi][vali])
            {
                b[xi][yi][vali] = b[x][y][val] + 1;

                Q.push(Tri(xi, yi, vali));


            }

        }
    }

}