Cod sursa(job #1159760)

Utilizator dariusdariusMarian Darius dariusdarius Data 29 martie 2014 20:50:16
Problema Kdrum Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.85 kb
#include <algorithm>
#include <fstream>
#include <map>
#include <queue>
#include <vector>
using namespace std;
const int MAX_N = 52;
const int MAX_K = 12005;
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 index[MAX_K];
vector<int> divisors;

inline int gcd(int x, int y) {
    return y ? gcd(y, x % y) : x;
}

int main() {
    ifstream fin("kdrum.in");
    ofstream fout("kdrum.out");
    int n, m, k, x1, y1, x2, y2;
    fin >> n >> m >> k;
    for(int i = 1; i <= k; ++ i) {
        if(k % i == 0) {
            divisors.push_back(i);
            index[i] = divisors.size() - 1;
        }
    }
    fin >> x1 >> y1 >> x2 >> y2;
    for(int i = 1; i <= n; ++ i) {
        for(int j = 1; j <= m; ++ j) {
            fin >> values[i][j];
            if(values[i][j]) {
                values[i][j] = gcd(values[i][j], k);
            }
        }
    }
    q.push(Node(x1, y1, index[values[x1][y1]]));
    cost[x1][y1][index[values[x1][y1]]] = 1;
    while(!q.empty()) {
        int x = q.front().x;
        int y = q.front().y;
        int rest = divisors[q.front().rest];
        for(int i = 0; i < 4; ++ i) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            int nrest = gcd(rest * values[nx][ny], k);
            if(values[nx][ny] != 0 && cost[nx][ny].count(index[nrest]) == 0) {
                q.push(Node(nx, ny, index[nrest]));
                cost[nx][ny][index[nrest]] = cost[x][y][index[rest]] + 1;
                if(nx == x2 && ny == y2 && nrest == k) {
                    fout << cost[nx][ny][index[nrest]] << "\n";
                    return 0;
                }
            }
        }
        q.pop();
    }
    return 0;
}