Cod sursa(job #2654368)

Utilizator mariamirabella2Bucur-Sabau Maria-Mirabela mariamirabella2 Data 30 septembrie 2020 17:34:50
Problema Kdrum Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.25 kb
#include <fstream>
#include <queue>
#include <algorithm>

using namespace std;
ofstream cout("kdrum.out");
class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};
InParser cin("kdrum.in");

struct idk{
    int i,j,mod;
};
const int vx[]={0,1,0,-1},vy[]={1,0,-1,0};
int n,m,k,x1,y1,x2,y2,nr,nrd[125],d[12005],v[55][55],dp[55][55][125];
queue <idk> q;

int main()
{
    cin>>n>>m>>k>>x1>>y1>>x2>>y2;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
        cin>>v[i][j];
        }
    }
    for (int i = 1; i <= k; i++) {
        if (k % i == 0) {
            nrd[++nr] = i;
            d[i] = nr;
        }
    }
    int a=d[__gcd(v[x1][y1], k)];
    q.push({x1,y1,a});
    dp[x1][y1][a]=1;
    while(!q.empty()){
        int i=q.front().i;
        int j=q.front().j;
        int poz1=q.front().mod;
        q.pop();
        for (int l=0;l<4;l++) {
            int xx = i + vx[l];
            int yy = j + vy[l];
            if (v[xx][yy] != 0) {
                int poz2=d[nrd[poz1] * __gcd(k/nrd[poz1], v[xx][yy])];
                if (dp[xx][yy][poz2] == 0) {
                    dp[xx][yy][poz2]=dp[i][j][poz1] + 1;
                    q.push({xx, yy, poz2});
                    if(xx == x2 && yy == y2 && poz2== nr){
                        cout<<dp[x2][y2][nr];
                        return 0;
                    }
                }
            }
        }
    }
    return 0;
}