Cod sursa(job #860614)

Utilizator Catah15Catalin Haidau Catah15 Data 20 ianuarie 2013 14:35:25
Problema Kdrum Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.77 kb
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <queue>

using namespace std;

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


int A[maxN][maxN], Diiv[maxN + maxN];
int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1};
queue < pair < pair <int, int>, int> > Q;
int Cost[maxN][maxN][maxN + maxN];
int Nrd[maxK];


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


int main()
{
    ifstream f ("kdrum.in");
    ofstream g ("kdrum.out");

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

    f >> N >> M >> K;
    f >> x1 >> y1 >> x2 >> y2;

    for (int i = 1; i <= N; ++ i)
        for (int j = 1; j <= M; ++ j)   f >> A[i][j];
    for (int i = 1; i <= K; ++ i) if (! (K % i)) Nrd[i] = ++ Nrd[0], Diiv[Nrd[0]] = i;


    Q.push ( MKP ( MKP (x1, y1), Nrd[gcd (K, A[x1][y1])]) );
    Cost[x1][y1][Nrd[gcd (K, A[x1][y1])]] = 1;

    while (! Q.empty ())
    {
        int x = Q.front().f.f, y = Q.front().f.s;
        int nrDiv = Q.front().s;

        Q.pop();

        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;

            int diviz = gcd (Diiv[nrDiv] * A[xx][yy], K);

            if (Cost[xx][yy][Nrd[diviz]]) continue;

            Cost[xx][yy][Nrd[diviz]] = Cost[x][y][nrDiv] + 1;

            if (xx == x2 && yy == y2 && diviz == K)
            {
                 g << Cost[x2][y2][Nrd[K]];
                 return 0;
            }

            Q.push ( MKP ( MKP (xx, yy), Nrd[diviz] ) );
        }
    }

    return 0;
}