Cod sursa(job #2534809)

Utilizator dorufDoru Floare doruf Data 30 ianuarie 2020 22:42:08
Problema Kdrum Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.52 kb
#include <bits/stdc++.h>
using namespace std;

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 fin("kdrum.in");
ofstream fout("kdrum.out");

struct Cel {int i, j, v;};

const int di[] = {0, 0, 1, -1};
const int dj[] = {1, -1, 0, 0};

#define iv (di[d] + i)
#define jv (dj[d] + j)

const int Inf = 0x3f3f3f3f;
const int N = 55, M = 55, V = 155, K = 12005;

int dp[N][M][V], a[N][M], dv[K];
int n, m, k, ip, jp, is, js;

inline bool Ok(const int& i, const int& j);
int gcd(int a, int b);
void Setup();
void Lee();

int main()
{
	Setup();
	Lee();
	fout << dp[is][js][dv[k]];
}

void Lee()
{
	queue<Cel> Q;
	Q.push({ip, jp, gcd(a[ip][jp], k)});
	dp[ip][jp][dv[gcd(a[ip][jp], k)]] = 1;

	int i, j, v;
	while (!Q.empty())
	{
		i = Q.front().i;
		j = Q.front().j;
		v = Q.front().v;
		Q.pop();
		for (int d = 0; d < 4; ++d)
			if (Ok(iv, jv))
			{
				int newg = v * a[iv][jv];
				newg = gcd(k, newg);
				if (dp[iv][jv][dv[newg]] > dp[i][j][dv[v]] + 1)
				{
					dp[iv][jv][dv[newg]] = dp[i][j][dv[v]] + 1;
					Q.push({iv, jv, newg});
				}
			}
	}
}

void Setup()
{
	for (int i = 0; i < N; ++i)
	  for (int j = 0; j < M; ++j)
		for (int v = 0; v < V; ++v)
			dp[i][j][v] = Inf;

	fin >> n >> m >> k;
	fin >> ip >> jp >> is >> js;
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j)
			fin >> a[i][j];

	int curr = 0;
	for (int i = 1; i <= k; ++i)
		if (k % i == 0) dv[i] = ++curr;
}

int gcd(int a, int b)
{
    int c;
    while (b) {
        c = a % b;
        a = b;
        b = c;
    }
    return a;
}

inline bool Ok(const int& i, const int& j)
{ return (i > 0 && j > 0 && i <= n && j <= m && a[i][j]); }