Cod sursa(job #1006712)

Utilizator DaNutZ2UuUUBB Bora Dan DaNutZ2UuU Data 7 octombrie 2013 16:49:02
Problema Kdrum Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.74 kb
#include <fstream>
#include <queue>

#include <cstring>
using namespace std;

const int MAX_N = 52;
const int MAX_K = 12002;
const int INF = 0x3f3f3f3f;

typedef struct node{
    int x, y, ind;
};

int N, M, K, X1, Y1, X2, Y2, NrDiv;
int A[MAX_N][MAX_N], B[MAX_N][MAX_N][302], Div[302], m[MAX_K];
queue < node > Q;

inline int cmmdc(int a, int b){
    int r;
    while(b){
        r = a % b;
        a = b;
        b = r;
    }
    return a;
}

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

    f >> N >> M >> K >> 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 == 0)
            ++NrDiv, Div[NrDiv] = i, m[i] = NrDiv;
       
    memset(B, INF, sizeof(B));    
    node T;
    T.x = X1, T.y = Y1, T.ind = m[cmmdc(A[X1][Y1], K)];
    B[X1][Y1][T.ind] = 1;
    Q.push(T);
    while(!Q.empty()){
        T = Q.front();
        Q.pop();
        for(int i = -1; i <= 1; ++i)
            for(int j = -1; j <= 1; ++j)
                if(i + j != 0 && i*j == 0){
                    int x1 = T.x + i, y1 = T.y + j;
                    if(A[x1][y1] == 0)
                        continue;
                    int p = Div[T.ind] * A[x1][y1];
                    p = cmmdc(p, K);
                    if(B[T.x][T.y][T.ind] + 1 < B[x1][y1][m[p]]){
                        node R;
                        R.x = x1, R.y = y1, R.ind = m[p];
                        Q.push(R);
                        B[x1][y1][R.ind] = B[T.x][T.y][T.ind] + 1;
                    }
                }
    }

    g << B[X2][Y2][NrDiv] << '\n';

    f.close();
    g.close();

    return 0;
}