Cod sursa(job #2574990)

Utilizator gavra_bogdanBogdan Gavra gavra_bogdan Data 6 martie 2020 11:03:34
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.88 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <queue>
#define pi pair<int,int>
#define x first
#define y second

using namespace std;

const int nmax = 1e3 + 5;

bool viz[nmax][nmax];
int d[nmax][nmax],v[nmax][nmax];
int dx[4] = { -1,0,1,0 };
int dy[4] = { 0,1,0,-1 };
queue<pi>q;

bool isin(pi z, int n, int m) {
	return (z.x > 0 and z.y > 0 and z.x <= n and z.y <= m);
}

void build_dist(int n,int m){
	while (!q.empty()) {
		auto z = q.front();
		q.pop();
		for (int i = 0; i < 4; i++) {
			pi vec = { z.x + dx[i],z.y + dy[i] };
			if (isin(vec, n, m) and !viz[vec.x][vec.y] and !v[vec.x][vec.y]) {
				q.push(vec);
				viz[vec.x][vec.y] = 1;
				d[vec.x][vec.y] = d[z.x][z.y] + 1;
			}
		}
	}
}

bool lee(pi start, pi finish, int k, int n, int m) {
	while (!q.empty())
		q.pop();
	memset(viz, 0, sizeof(viz));
	q.push(start);
	viz[start.x][start.y] = 1;
	if (d[start.x][start.y] < k)
		return 0;
	while (!q.empty()) {
		auto z = q.front();
		q.pop();
		if (z == finish)
			return 1;
		for (int i = 0; i < 4; i++) {
			pi vec = { z.x + dx[i],z.y + dy[i] };
			if (isin(vec, n, m) and !viz[vec.x][vec.y] and d[vec.x][vec.y] >= k) {
				q.push(vec);
				viz[vec.x][vec.y] = 1;
			}
		}
	}
	return 0;
}

int main()
{
	ifstream cin("barbar.in");
	ofstream cout("barbar.out");
	int n, m;
	char ch;
	pi start, finish;
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++) {
			cin >> ch;
			if (ch == 'I')
				start = { i,j };
			if (ch == 'O')
				finish = { i,j };
			if (ch == 'D')
				viz[i][j] = 1, q.push({ i,j });
			if (ch == '*')
				v[i][j] = 1;
		}
	build_dist(n, m);
	int st = 0, dr = 1e9, ans;
	while (st <= dr) {
		int mijl = (st + dr) / 2;
		bool ok = lee(start, finish, mijl, n, m);
		if (ok) {
			st = mijl + 1;
			ans = mijl;
		}
		else
			dr = mijl - 1;
	}
	cout << ans;
}