Cod sursa(job #2651947)

Utilizator rares404AlShaytan - Balasescu Rares rares404 Data 23 septembrie 2020 20:14:56
Problema Kdrum Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.54 kb
//
//  main.cpp
//  kdrum
//
//  Created by Eusebiu Rares on 23/09/2020.
//  Copyright © 2020 Eusebiu Rares. All rights reserved.
//

#include <iostream>
#include "fstream"
#include "queue"

std::fstream in ("kdrum.in", std::ios::in) ;
std::fstream out ("kdrum.out", std::ios::out) ;

const int MV = 50 ;
const int MX = 12e3 ;
int mat[MV + 1][MV + 1] ;
int divizori[MV + 1] ;
int resp[MX + 1] ;
int dp[MV + 1][MV + 1][MV * 2 + 1] ;

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

int dx[] = {0, 1, -1, 0, 0};
int dy[] = {0, 0, 0, 1, -1};

struct cell {
	int x, y, p ;
} ;

int main(int argc, const char * argv[]) {
	int n, m, k, i, j ;
	in >> n >> m >> k ;
	int x1, y3, x2, y2 ;
	in >> x1 >> y3 >> x2 >> y2 ;
	for (i = 1 ; i <= n ; ++ i) {
		for (j = 1 ; j <= m ; ++ j) {
			in >> mat[i][j] ;
		}
	}
	int dd(0) ;
	for (i = 1 ; i <= k ; ++ i) {
		if (k % i == 0) {
			divizori[++ dd] = i ;
			resp[i] = dd ;
		}
	}
	dp[x1][y3][resp[gcd(k, mat[x1][y3])]] = 1 ;
	std::queue<cell> q ;
	q.push({x1, y3, resp[gcd(k, mat[x1][y3])]}) ;
	while (!q.empty()) {
		cell t = q.front() ;
		q.pop() ;
		if (t.x == x2 and t.y == y2 and t.p == dd) {
			std::cout << t.x << ' ' << t.y ;
			return out << dp[t.x][t.y][dd], 0 ;
		}
		int xx, yy ;
		for (i = 1 ; i <= 4 ; ++ i) {
			xx = t.x + dx[i] ;
			yy = t.y + dy[i] ;
			if (!mat[xx][yy]) {
				continue ;
			}
			int pp = resp[gcd(k, divizori[t.p] * mat[xx][yy])] ;
			if (dp[xx][yy][pp]) {
				continue ;
			}
			dp[xx][yy][pp] = dp[t.x][t.y][t.p] + 1 ;
			q.push({xx, yy, pp}) ;
		}
	}
}