Cod sursa(job #1541367)

Utilizator ElemelixEle Melix Elemelix Data 3 decembrie 2015 22:47:48
Problema Barbar Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.6 kb
#include <iostream>
#include <queue>
#include <fstream>

using namespace std;

int r, c;
char t[1001][1001];
char aux[1001][1001];
bool viz[1001][1001];

struct coord
{
	int x, y;
};

//void print()
//{
//	for (int i = 0; i < r; i++)
//	{
//		for (int j = 0; j < c; j++)
//			cout << aux[i][j] << " ";
//		cout << "\n";
//	}
//	getchar();
//}

bool ok(int d)
{
	int xstart, ystart;
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
		{
			viz[i][j] = false;
			aux[i][j] = t[i][j];
			if (aux[i][j] == 'D')
			{
				int n = i, s = i, e = j, w = j;
				while (n >= 0 && i - n < d)
				{
					if (aux[n][j] != 'D')
						aux[n][j] = '*';
					n--;
				}
				while (s < r && s - i < d)
				{
					if (aux[s][j] != 'D' && aux[s][j] != 'I' && aux[s][j] != 'O')
						aux[s][j] = '*';
					s++;
				}
				while (e < c && e - j < d)
				{
					if (aux[i][e] != 'D' && aux[i][e] != 'I' && aux[i][e] != 'O')
						aux[i][e] = '*';
					e++;
				}
				while (w >= 0 && j - w < d)
				{
					if (aux[i][w] != 'D' && aux[i][w] != 'I' && aux[i][w] != 'O')
						aux[i][w] = '*';
					w--;
				}
			}
			if (t[i][j] == 'I')
				xstart = i, ystart = j;
		}
//	print();
	for (int i = 0; i < c; i++)
		for (int j = 0; j < r; j++)
			viz[i][j] = 0;
	queue<coord> q;
	coord inc;
	inc.x = xstart;
	inc.y = ystart;
	q.push(inc);
	while (!q.empty())
	{
		coord c1 = q.front(), c2;
		q.pop();
		viz[c1.x][c1.y] = true;
		if (aux[c1.x][c1.y] == 'O')
			return true;
		if (c1.x + 1 < r && !viz[c1.x + 1][c1.y] && aux[c1.x + 1][c1.y] != 'D' && aux[c1.x + 1][c1.y] != '*')
			c2.x = c1.x + 1, c2.y = c1.y, q.push(c2);
		if (c1.y + 1 < c && !viz[c1.x][c1.y + 1] && aux[c1.x][c1.y + 1] != 'D' && aux[c1.x][c1.y + 1] != '*')
			c2.x = c1.x, c2.y = c1.y + 1, q.push(c2);
		if (c1.x - 1 >= 0 && !viz[c1.x - 1][c1.y] && aux[c1.x - 1][c1.y] != 'D' && aux[c1.x - 1][c1.y] != '*')
			c2.x = c1.x - 1, c2.y = c1.y, q.push(c2);
		if (c1.y - 1 >= 0 && !viz[c1.x][c1.y - 1] && aux[c1.x][c1.y - 1] != 'D' && aux[c1.x][c1.y - 1] != '*')
			c2.x = c1.x, c2.y = c1.y - 1, q.push(c2);
	}
	return false;
}
	
int bSearch(int first, int last)
{
	int found = -1;
	while (first <= last)
	{
		int mid = (first + last) / 2;
//		cout << mid << "\n";
		if (ok(mid))
		{
			found = mid;
			first = mid + 1;
		}
		else
			last = mid - 1;
	}
	return found;
}

int main()
{
	ifstream in("barbar.in");
	in >> r >> c;
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
			in >> t[i][j];
	in.close();
	ofstream out("barbar.out");
	out << bSearch(1, r + c);
	out.close();
	getchar();
}