Cod sursa(job #1657929)

Utilizator sandupetrascoPetrasco Sandu sandupetrasco Data 20 martie 2016 21:36:01
Problema Barbar Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.52 kb
#include <fstream>
#include <queue>

using namespace std;
typedef pair<int,int> PL;
const int dirx[] = {0,1,0,-1};
const int diry[] = {1,0,-1,0};

ifstream cin("barbar.in");
ofstream cout("barbar.out");
int N, M, dist[1002][1002], MA[1002][1002], d2[1002][1002], ix, iy, jx, jy;
bool viz[1002][1002];
queue<PL> QUEUE;
queue<PL> rs;
void Lee1(){
		for(int i = 0; i < N; i++)
			for(int j = 0; j < M; j++) 
				if(MA[i][j] == 1){
					QUEUE.push(make_pair(i,j));
					viz[i][j] = 1;	
					}
	
	while(!QUEUE.empty()){
		PL node = QUEUE.front();
		QUEUE.pop();
		for(int i = 0; i < 4; i++){
			int x = node.first + dirx[i];
			int y = node.second + diry[i];
			if(viz[x][y] == 0 && x >= 0 && x < N && y < M && y >= 0 && MA[x][y] == 0 && MA[x][y] == -2){
				viz[x][y] = 1;
				QUEUE.push(make_pair(x,y));
				dist[x][y] = dist[node.first][node.second]+1; 
					}
			}
		}
	}
bool check(int mid){
	for(int i = 0; i < N; i++)
			   for(int j = 0; j < M; j++) 
				viz[i][j] = 0;
	while(!rs.empty()) rs.pop();
	rs.push(make_pair(jx, jy));
	viz[jx][jy] = 1;
	int xi, yi;
	while(!rs.empty()){
		PL node = rs.front();
		rs.pop();	
	for(int i = 0; i < 4; i++){
		xi = node.first + dirx[i];
		yi = node.second + diry[i];
		if(viz[xi][yi] == 0 && xi >= 0 && xi < N && yi >= 0 && yi < M && dist[xi][yi] >= mid){
			viz[xi][yi] = 1;
			rs.push(make_pair(xi,yi));
			d2[xi][yi] = d2[node.first][node.second] + 1;
			}
		}
	}
	if(viz[ix][iy]) return 1;
	return 0;
}
char x;
int main(){
	cin >> N >> M;
		for(int i = 0; i < N; i++)
			for(int j = 0; j < M; j++){
				cin >> x;
			if(x == 'I'){ MA[i][j] = -1; jx = i; jy = j;}// Intrare: -1
			if(x == 'O'){ MA[i][j] = -2; ix = i; iy = j;}// Iesire: -2
			if(x == 'D') MA[i][j] = 1; // Dragon: 1
			if(x == '*') MA[i][j] = 2; // Perete: 2
		}
	Lee1();
	/*for(int i = 0; i < N; i++){
			for(int j = 0; j < M; j++) cout << MA[i][j] << " ";
		cout << '\n';
	}*/
	/*for(int i = 0; i < N; i++){
			for(int j = 0; j < M; j++) cout << dist[i][j] << " ";
		cout << '\n';
	}
	cout << '\n';*/
	
	
	int st = 0, dr = 1e9;
	while(st <= dr){
		int mid = (st+dr)/2;
		//cout << mid << "\n";
		if(check(mid)) st = mid + 1;
			else dr = mid - 1;
		/*for(int i = 0; i < N; i++){
			for(int j = 0; j < M; j++) cout << d2[i][j] << " ";
		cout << '\n';
	}
	cout << '\n';*/
		}
	if(st == 0) cout << -1;		
		else cout << st+1;
	/*for(int i = 0; i < N; i++){
			for(int j = 0; j < M; j++) cout << dist[i][j] << " ";
		cout << '\n';
	}
	cout << '\n';*/
	
	return 0;
}