Cod sursa(job #256494)

Utilizator vlad_DVlad Dumitriu vlad_D Data 11 februarie 2009 20:26:51
Problema Kdrum Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.24 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <map>
using namespace std;

int N, M, K;
int sx, sy, fx, fy;
int harta[55][55];
map<pair<int, int>, int> MAP;
int di[] = {-1, 1, 0, 0};
int dj[] = {0, 0, -1, 1};
int main() {
	ifstream fin("kdrum.in");
	ofstream fout("kdrum.out");
	
	//read the data
	fin >> N >> M >> K;
	fin >> sx >> sy >> fx >> fy;
	for (int i = 1; i <= N; ++i)
		for (int j  = 1; j <= M; ++j) fin >> harta[i][j];
	
	//im cool
	MAP[make_pair(sx*100 + sy,int( __gcd(K, harta[sx][sy])))] = 1;
	queue<pair<int, int> > Q;
	Q.push(make_pair(sx*100 + sy, __gcd(K, harta[sx][sy])));
	int solution = -1;
	while (!Q.empty()) {
		pair<int, int> state = Q.front(); Q.pop();
		int steps = MAP[state];
		int px = state.first/100, py = state.first % 100;
		if (state.second == K && px == fx && py == fy) {solution = steps; break;}
		//deplaseaza
		for (int d = 0; d < 4; ++d) {
			int nx = di[d] +px;
			int ny = dj[d] + py;
			if (harta[nx][ny] == 0) continue;
			int prod = __gcd(state.second * harta[nx][ny], K);
			if (MAP[make_pair(nx*100 + ny, prod)]) continue;	
			MAP[make_pair(nx*100 + ny, prod)] = steps + 1;
			Q.push(make_pair(nx*100 + ny, prod));
			}
		}
	fout << solution << '\n';
	fout.close();
	}