Cod sursa(job #1061692)

Utilizator antonioteoZait Teodor Antonio antonioteo Data 20 decembrie 2013 10:04:33
Problema Matrice 2 Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.56 kb
#include <algorithm>
#include <iostream>
#include <cstring>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream fin("matrice2.in");
ofstream fout("matrice2.out");

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

#define NMAX 301
#define lim (1 << 20)

#define PII pair <int, int>
#define mp make_pair
#define x first
#define y second

int i, j, N, QA;
int x1, x2, y1, y2;
int CMAX;

int a[NMAX][NMAX];
bool Used[NMAX][NMAX];

queue <PII> Q;

inline int isOk(int a, int b){if (a >= 1 && a <= N && b >= 1 && b <= N) return 1; return 0;}

int isRoad(int Cost) {
	if (Cost > a[x1][y1] || Cost > a[x2][y2]) return 0;
	memset(Used, 0, sizeof(Used));
	while (!Q.empty()) Q.pop();
	PII acm;
	Q.push(mp(x1, y1));
	Used[x1][y1] = true;
	while (!Q.empty()) {
		acm = Q.front();
		Q.pop();
		PII ret;
		for (int k = 0; k < 4; ++k) {
			ret.x = acm.x + dx[k];
			ret.y = acm.y + dy[k];
			if (isOk(ret.x, ret.y) && !Used[ret.x][ret.y] && a[ret.x][ret.y] >= Cost) {
				Used[ret.x][ret.y] = true;
				if (Used[x2][y2] == true) 
					return 1;
				Q.push(ret);
			}
		}
	}
	return 0;
}

inline int Binary_Search() {
	int cnt, i;
	for (i = 0, cnt = lim; cnt; cnt >>= 1) {
		if (i + cnt <= CMAX && isRoad(i + cnt))
			i += cnt;
	}
	return i;
}

int main() {
	fin >> N >> QA;
	for (i = 1; i <= N; ++i)
		for (j = 1; j <= N; ++j)
			fin >> a[i][j], 
			CMAX = max(CMAX, a[i][j]);
	for (j = 1; j <= QA; ++j) {
		fin >> x1 >> y1 >> x2 >> y2;
		fout << Binary_Search() << '\n';
	}
	return 0;
}