Cod sursa(job #1023583)

Utilizator brainwashed20Alexandru Gherghe brainwashed20 Data 7 noiembrie 2013 12:43:41
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.63 kb
#include<fstream>
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>

using namespace std;

#define x first
#define y second
#define mp make_pair

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

ifstream f("barbar.in");
ofstream g("barbar.out");

int mat[MatrixSize][MatrixSize],  new_mat[MatrixSize][MatrixSize], n, m, rez;
pair<int, int> inc, sf;

void bf_dragons(vector<pair<int, int> >& dragons) {

	queue<pair<int, int> > q;
	pair<int, int> firstelem;
	int k, lin, col, new_lin, new_col;

	for (k = 0; k < (int) dragons.size(); ++k)
		q.push(dragons[k]);

	while (!q.empty()) {
		firstelem = q.front();
		lin = firstelem.x;
		col = firstelem.y;
		q.pop();
		for (k = 0; k < 4; ++k) {
			new_lin = dx[k] + firstelem.x;
			new_col = dy[k] + firstelem.y;
			if (new_lin > 0 && new_lin <= n && new_col > 0 && new_lin <= m) {
				if (mat[new_lin][new_col] == 0) {
					mat[new_lin][new_col] = mat[lin][col] + 1;
					q.push(mp(new_lin, new_col));
				}
			}
		}
	}
}

int valid(int val) {

	int i, j, k, lin, col, new_lin, new_col;
	pair<int, int> firstelem;
	queue<pair<int, int> > q;

	for (i = 1; i <= n; ++i)
		for (j = 1; j <= m; ++j)
			new_mat[i][j] = mat[i][j];

	if (new_mat[inc.x][inc.y] <= val)
		return 0;

	new_mat[inc.x][inc.y] = -1;
	q.push(inc);

	while (!q.empty()) {
		firstelem = q.front();
		lin = firstelem.x;
		col = firstelem.y;
		q.pop();
		for (k = 0; k < 4; ++k) {
			new_lin = dx[k] + firstelem.x;
			new_col = dy[k] + firstelem.y;
			if (new_lin > 0 && new_lin <= n && new_col > 0 && new_lin <= m) {
				if (new_mat[new_lin][new_col] == 0
						|| new_mat[new_lin][new_col] > val) {
					new_mat[new_lin][new_col] = 1;
					q.push(mp(new_lin, new_col));
					if (new_lin == sf.x && new_col == sf.y)
						return 1;
				}
			}
		}
	}

	return 0;
}

int main() {

	char ch;
	int i, j, st, dr, mij;
	vector<pair<int, int> > dragons;

	f >> n >> m;
	for (i = 1; i <= n; ++i)
		for (j = 1; j <= m; ++j) {
			f >> ch;
			if (ch == 'D') {
				dragons.push_back(mp(i, j));
				mat[i][j] = 1;
				continue;
			}
			if (ch == '*') {
				mat[i][j] = 1;
				continue;
			}
			if (ch == 'I') {
				inc = mp(i, j);
				continue;
			}
			if (ch == 'O') {
				sf = mp(i, j);
				continue;
			}
		}

	bf_dragons(dragons);

	st = 1;
	dr = max(n, m);

	while (st <= dr) {
		mij = (st + dr) / 2;
		if (valid(mij) == 1) {
			rez = mij;
			st = mij + 1;
		} else
			dr = mij - 1;
	}

	if (rez)
		g << rez << "\n";
	else
		g << "-1" << "\n";

	f.close();
	g.close();

	return 0;
}