Cod sursa(job #900138)

Utilizator tudorv96Tudor Varan tudorv96 Data 28 februarie 2013 17:50:22
Problema Barbar Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.73 kb
#include <fstream>
#include <queue>
using namespace std;

int m, n, M, sol;
int a[1005][1005];
bool b[1005][1005];

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

struct coord {
	int x,y;
} s, f;

queue <coord> Q;
coord init (int x, int y)
{
	coord a;
	a.x = x, a.y = y;
	return a;
}

bool Try (int d)
{
	while (Q.size())
		Q.pop();
	Q.push (s);
	b[s.x][s.y] = 1;
	while (!(Q.front().x == f.x && Q.front().y == f.y) && !Q.empty())
	{
		int i = Q.front().x;
		int j = Q.front().y;
		for (int k = 0; k < 4; ++k)
		{
			int ii = i + dx[k];
			int jj = j + dy[k];
			if (ii >= 0 && jj >= 0 && ii < m && jj < n && a[ii][jj] >= d && !b[ii][jj])
				Q.push (init (ii,jj)), b[ii][jj] = 1;
		}
		Q.pop();
	}
	for (int i = 0; i < m; ++i)
		for (int j = 0; j < n; ++j)
			b[i][j] = 0;
	if (Q.empty())
		return false;
	return true;
}

int main ()
{
	ifstream fin ("barbar.in");
	fin >> m >> n;
	for (int i = 0; i < m; ++i)
		for (int j = 0; j < n; ++j)
		{
			char ioi;
			fin >> ioi;
			if (ioi == 'I')
				s.x = i, s.y = j;
			if (ioi == 'O')
				f.x = i, f.y = j;
			if (ioi == '*')	
				a[i][j] = -1;
			if (ioi == 'D')
				Q.push (init (i, j)), a[i][j] = 1;
		}
	fin.close();
	while (!Q.empty())
	{
		int i = Q.front().x;
		int j = Q.front().y;
		for (int k = 0; k < 4; ++k)
		{
			int ii = i + dx[k];
			int jj = j + dy[k];
			if (ii >= 0 && jj >= 0 && ii < m && jj < n && !a[ii][jj])
			{
				a[ii][jj] = a[i][j] + 1;
				M = a[ii][jj];
				Q.push (init (ii, jj));
			}
		}
		Q.pop();
	}
	M = min (M, min (a[s.x][s.y], a[f.x][f.y]));
	int hi = M, lo = 2;
	while (lo <= hi)
	{
		int mid = (hi + lo) / 2;
		if (Try (mid))
		{
			sol = mid;
			lo = mid + 1;
		}
		else
			hi = mid - 1;
	}
	ofstream fout ("barbar.out");
	fout << sol - 1;
	fout.close();
	return 0;	
}