Cod sursa(job #128246)

Utilizator andrei.12Andrei Parvu andrei.12 Data 26 ianuarie 2008 18:47:54
Problema Barbar Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.93 kb
#include<stdio.h>
#define lg 1005
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, -1, 1};
int n, m, i, j, st, end, x, y, xx, yy, a[lg][lg], rezultat, cost[lg][lg], mx, px, py, fx, fy;
char s[lg], fst[lg][lg], drg[lg][lg];
struct queue{
	int x, y, l;
};
queue q[lg*lg];
void gol(){
	for (int i = 1; i <= n; i ++)
		for (int j = 1; j <= m; j ++)
			fst[i][j] = 0;
}
int check(int val){
	int st = 1, end = 1, x, y, xx, yy;
	
	gol();
	q[1].x = px;
	q[1].y = py;
	while (st <= end){
		x = q[st].x;
		y = q[st].y;
		
		for (int i = 0; i < 4; i ++){
			xx = x+dx[i];
			yy = y+dy[i];
			
			if (xx <= n && xx > 0 && yy <= m && yy > 0)
				if (!fst[xx][yy] && cost[xx][yy] >= val && !a[xx][yy]){
					fst[xx][yy] = 1;
					end ++;
					q[end].x = xx;
					q[end].y = yy;
				}
		}
		
		st ++;
	}
	
	if (fst[fx][fy])
		return 0;
	return 1;
}
int bs(){
	int li = 0, ls = mx, gs = -1, x, s;
	
	while (li <= ls){
		x = (li+ls) / 2;
		
		s = check(x);
		if (!s){
			gs = x;
			li = x+1;
		}
		else
			ls = x-1;
	}
	
	return gs;
}
int main()
{
	freopen("barbar.in", "rt", stdin);
	freopen("barbar.out", "wt", stdout);
	
	scanf("%d%d", &n, &m);
	for (i = 1; i <= n; i ++){
		scanf("%s", s);
		for (j = 0; j < m; j ++){
			if (s[j] == '*')
				a[i][j+1] = 1;
			if (s[j] == 'D')
				q[++end].x = i, q[end].y = j+1, drg[i][j+1] = 1;
			if (s[j] == 'I')
				px = i, py = j+1;
			if (s[j] == 'O')
				fx = i, fy = j+1;
		}
	}
	
	st = 1;
	while (st <= end){
		x = q[st].x;
		y = q[st].y;
		
		for (i = 0; i < 4; i ++){
			xx = x+dx[i];
			yy = y+dy[i];
			
			if (!a[xx][yy] && xx <= n && xx > 0 && yy <= m && yy > 0)
				if (!drg[xx][yy]){
					drg[xx][yy] = 1;
					
					end ++;
					q[end].x = xx;
					q[end].y = yy;
					q[end].l = q[st].l+1;
					cost[xx][yy] = q[end].l;
				}
		}
		
		st ++;
	}
	
	mx = n*m;
	rezultat = bs();
	
	printf("%d\n", rezultat);
	
	return 0;
}