Cod sursa(job #2836851)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 20 ianuarie 2022 23:57:00
Problema Kdrum Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.79 kb
#include <iostream>
#include <fstream>
#include <queue>

using namespace std;

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

int n, m, k, x1, y1, x2, y2;
int mat[55][55], diviz[12005], nr_diviz;
int dp[55][55][200];
int dlin[] = {0, 1, 0, -1}, dcol[] = {1, 0, -1, 0};

struct coords{
    int x, y, val;
};
queue <coords> q;

bool InBounds(int a, int b)
{
    return 0 < a && a <= n && 0 < b && b <= m;
}

int euclid(int a, int b)
{
    if(a == 0 || b == 0)
        return 0;
    int r = a % b;
    while (r)
    {
        a = b;
        b = r;
        r = a % b;
    }
    return b;
}

int main()
{
    fin >> n >> m >> k >> x1 >> y1 >> x2 >> y2;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
        {
            fin >> mat[i][j];
            mat[i][j] = euclid(mat[i][j], k);
        }
    for(int i = 1; i <= k; i++)
        if(k % i == 0)
            diviz[i] = ++nr_diviz;
    dp[x1][y1][diviz[mat[x1][y1]]] = 1;
    q.push({x1, y1, mat[x1][y1]});
    while(!q.empty())
    {
        int x = q.front().x, y = q.front().y, val = q.front().val;
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            int nx = x + dlin[i], ny = y + dcol[i];
            if(InBounds(nx, ny))
            {
                int aux = euclid(val * mat[nx][ny], k);
                if(!dp[nx][ny][diviz[aux]])
                {
                    dp[nx][ny][diviz[aux]] = dp[x][y][diviz[val]] + 1;
                    q.push({nx, ny, aux});
                    if(nx == x2 && ny == y2 && aux == k)
                    {
                        fout << dp[x2][y2][diviz[k]];
                        return 0;
                    }
                }
            }
        }
    }
    fout << dp[x2][y2][diviz[k]];
    return 0;
}