Pagini recente » Cod sursa (job #2987235) | Cod sursa (job #1314570) | Cod sursa (job #1218406) | Cod sursa (job #159117) | Cod sursa (job #2836849)
#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 a + b;
if(a > b)
return euclid(a % b, b);
else
return euclid(a, b % a);
}
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;
}