Cod sursa(job #2110942)

Utilizator SqueekDanielTodasca Daniel SqueekDaniel Data 21 ianuarie 2018 15:18:28
Problema Kdrum Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.54 kb
#include <fstream>
#include <queue>
std::ifstream f("kdrum.in");
std::ofstream g("kdrum.out");

int N, M, K;
int nr[55][55];
int y1, x1, y2, x2;
int fct[505], fct_index[12005], nrf;
int gcd(int a, int b) {
    int r;
    while(b!=0) r=a%b, a=b, b=r;
    return a;
} void calc() {
    for (int i=1; i<=K; i++)
        if(K%i==0)
            fct[++nrf] = i, fct_index[i] = nrf;
}

void citeste() {
    f >> N >> M >> K;
    f >> y1 >> x1 >> y2 >> x2;
    for (int i=1, j; i<=N; i++)
        for (j=1; j<=M; j++)
            f >> nr[i][j];
}

int dx[]={0,0,-1,1}, dy[]={1,-1,0,0};
int pasi[55][55][505];
void lee() {
    struct nod {
        int y, x, fact;
    }; std::queue <nod> q;
    pasi[y1][x1][fct_index [gcd (K, nr[y1][x1])]] = 1;
    q.push({y1, x1, fct_index [gcd (K, nr[y1][x1])]});

    nod pres, nou;
    while(!q.empty()) {
        pres = q.front();
        q.pop();

        for (int i=0; i<4; i++) {
            nou = pres;
            nou.y += dy[i]; nou.x += dx[i];
            if(nr[nou.y][nou.x] != 0) {
                nou.fact = fct_index [gcd (K, fct[pres.fact]*nr[nou.y][nou.x])];

                if(pasi[nou.y][nou.x][nou.fact] == 0 || pasi[nou.y][nou.x][nou.fact] > pasi[pres.y][pres.x][pres.fact] + 1) {
                    pasi[nou.y][nou.x][nou.fact] = pasi[pres.y][pres.x][pres.fact] + 1;
                    q.push(nou);
                }
            }
        }
     }
}

int main()
{
    citeste();
    calc();
    lee();
    g << pasi[y2][x2][fct_index[K]];

    return 0;
}