Cod sursa(job #1898176)

Utilizator FloareaCucura Floarea Ludovica Floarea Data 1 martie 2017 21:00:27
Problema Kdrum Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.85 kb
#include <fstream>
#include <queue>

using namespace std;

struct mp{
       int x;
       int y;
       int z;
       mp(int _x, int _y, int _z): x(_x), y(_y), z(_z){}
};

int n, m, k, x1, x2, y1, y2, a[55][55], l[55][55][200];
int fact[200];
int poz[12002];
int nrdiv;

queue <mp> Q;

int cmmdc(int a,int b)
{
    if(b==0)
        return a;
    return cmmdc(b,a%b);
}

int main()
{
    ifstream fin("kdrum.in");
    ofstream fout("kdrum.out");
    fin >> n >> m >> k;
    fin >> x1 >> y1 >> x2 >> y2;
    for(int i = 1 ; i <= n ; ++ i)
            for(int j = 1 ; j <= m ; ++ j)
                    fin >> a[i][j];

    for(int i = 1 ; i <= k ; ++ i)
            if(k % i == 0)
            {
                 fact[++nrdiv] = i;
                 poz[i] = nrdiv;
            }
    int dx[4] = {-1, 0, 1, 0};
    int dy[4] = { 0, 1, 0, -1};
    l[x1][y1][  poz[cmmdc(k, a[x1][y1] )]  ] = 1;
    for(Q.push(mp(x1, y1, poz[    cmmdc( k, a[x1][y1] )   ] )); !Q.empty() ; Q.pop() )
    {
                      int x = Q.front().x;
                      int y = Q.front().y;
                      int z = Q.front().z;
                      for(int i = 0 ; i < 4; ++ i)
                      {
                           int xnou = x + dx[i];
                           int ynou = y + dy[i];
                           if(xnou<1 || xnou >n || ynou<1 || ynou>m || !a[xnou][ynou]  ) continue;
                           int  t = poz[   cmmdc(k, fact[z]*a[xnou][ynou])    ];
                           if(!l[xnou][ynou][t] || l[xnou][ynou][t] > l[x][y][z] +1 )
                           {
                                     l[xnou][ynou][t]=l[x][y][z]+1;
                                     Q.push(mp(xnou,ynou,t));
                           }
                      }
    }
    fout << l[x2][y2][nrdiv] << "\n";

    return 0;
}