Pagini recente » Cod sursa (job #2264625) | Cod sursa (job #467991) | Cod sursa (job #2495582) | Cod sursa (job #2905375) | Cod sursa (job #1159741)
#include <algorithm>
#include <fstream>
#include <map>
#include <queue>
#include <vector>
using namespace std;
const int MAX_N = 52;
const int dx[] = {0, 1, 0, -1};
const int dy[] = {-1, 0, 1, 0};
struct Node {
int x, y, rest;
Node() {}
Node(int xx, int yy, int rrest) {
x = xx; y = yy; rest = rrest;
}
};
queue<Node> q;
map<int, int> cost[MAX_N][MAX_N];
int values[MAX_N][MAX_N];
int main() {
ifstream fin("kdrum.in");
ofstream fout("kdrum.out");
int n, m, k, x1, y1, x2, y2;
fin >> n >> m >> k;
fin >> x1 >> y1 >> x2 >> y2;
for(int i = 1; i <= n; ++ i) {
for(int j = 1; j <= m; ++ j) {
fin >> values[i][j];
}
}
q.push(Node(x1, y1, values[x1][y1]));
cost[x1][y1][values[x1][y1]] = 1;
while(!q.empty()) {
int x = q.front().x;
int y = q.front().y;
int rest = q.front().rest;
for(int i = 0; i < 4; ++ i) {
int nx = x + dx[i];
int ny = y + dy[i];
int nrest = (1LL * rest * values[nx][ny]) % k;
if(values[nx][ny] != 0 && cost[nx][ny].count(nrest) == 0) {
q.push(Node(nx, ny, nrest));
cost[nx][ny][nrest] = cost[x][y][rest] + 1;
if(nx == x2 && ny == y2 && nrest == 0) {
fout << cost[nx][ny][nrest] << "\n";
return 0;
}
}
}
q.pop();
}
return 0;
}