Cod sursa(job #860582)

Utilizator Catah15Catalin Haidau Catah15 Data 20 ianuarie 2013 13:26:43
Problema Kdrum Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.51 kb
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <deque>

using namespace std;

#define maxN 55
#define PB push_back
#define MKP make_pair
#define int64 long long
#define f first
#define s second


int A[maxN][maxN];
int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1};
deque < pair < pair <int, int>, pair <int, int> > > Q;


inline int64 gcd (int64 A, int64 B)
{
    if (! B) return A;
    return gcd (B, A % B);
}


int main()
{
    freopen ("kdrum.in", "r", stdin);
    freopen ("krdum.out", "w", stdout);

    int N, M, K;
    int x1, y1, x2, y2;

    scanf ("%d %d %d", &N, &M, &K);

    scanf ("%d %d %d %d", &x1, &y1, &x2, &y2);

    for (int i = 1; i <= N; ++ i)
        for (int j = 1; j <= M; ++ j) scanf ("%d", &A[i][j]);

    Q.PB ( MKP ( MKP (x1, y1), MKP (gcd (A[x1][y1], K) , 1) ) );

    while (! Q.empty ())
    {
        int x = Q[0].f.f, y = Q[0].f.s;
        int64 Div = Q[0].s.f;
        int cost = Q[0].s.s;
        Q.pop_front();

        for (int t = 0; t < 4; ++ t)
        {
            int xx = x + dx[t], yy = y + dy[t];
            if (xx < 1 || xx > N || yy < 1 || yy > M) continue;
            if (! A[xx][yy]) continue;

            Div = Div * A[xx][yy];
            Div = gcd (Div, K);

            if (Div == K && xx == x2 && yy == y2)
            {
                printf ("%d", cost + 1);
                return 0;
            }

            Q.PB ( MKP ( MKP (xx, yy), MKP (Div, cost + 1) ) );
        }
    }

    return 0;
}