Cod sursa(job #845059)

Utilizator stoicatheoFlirk Navok stoicatheo Data 30 decembrie 2012 13:34:10
Problema Kdrum Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.77 kb
#include <fstream>
#include <queue>
using namespace std;
 
struct stu
{
    int first,second;
    int cm;
};
 
const int dx[]={1,0,-1,0};
const int dy[]={0,1,0,-1};
int N,M,K,a[55][55],ap[12100];
int p[55][55][100];
pair<int,int> st,fn;
queue<stu> Q;
 
inline int cmmdc(int a,int b)
{
    if(b==0) return a;
    return cmmdc(b,a%b);
}
 
inline stu make_stu(int a,int b,int c)
{
    stu ics;
    ics.first=a;
    ics.second=b;
    ics.cm=c;
    return ics;
}
 
int main()
{
    ifstream in("kdrum.in");
    ofstream out("kdrum.out");
     
    in>>N>>M>>K;
    in>>st.first>>st.second>>fn.first>>fn.second;
     
    for(int i=1;i<=N;++i)
    {
        for(int j=1;j<=M;++j)
        {
            in>>a[i][j];
        }
    }
     
    int lenght=1;
    for(int i=1;i<=K;++i)
    {
        if(K%i==0)
        {
            ap[i]=(++lenght);
        }
    }
     
    int nr;
    nr=cmmdc(K,a[st.first][st.second]);
    Q.push(make_stu(st.first,st.second,nr));
    p[st.first][st.second][ap[nr]]=1;
     
    for(;!Q.empty();Q.pop())
    {
        stu ret=Q.front();
        for(int k=0;k<4;++k)
        {
            stu acm=ret;
            acm.first+=dx[k];
            acm.second+=dy[k];
            acm.cm=cmmdc(K,acm.cm*a[acm.first][acm.second]);
             
            if(acm.first>0 && acm.first<=N && acm.second>0 && acm.second<=M)
            {
                if(p[acm.first][acm.second][ap[acm.cm]]==0 && a[acm.first][acm.second])
                {
                    p[acm.first][acm.second][ap[acm.cm]]=p[ret.first][ret.second][ap[ret.cm]]+1;
                    Q.push(acm);
                }
            }
        }
    }
     
    out<<p[fn.first][fn.second][ap[K]]<<'\n';
    out.close();
    return 0;
}