Cod sursa(job #449543)

Utilizator AndreiRSStatescu Andrei Rares AndreiRS Data 6 mai 2010 16:14:00
Problema Barbar Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.97 kb
#include <stdio.h>
#define DIM 1<<10

int di[4] = {0, -1, 0, 1};
int dj[4] = {1, 0, -1, 0};

FILE *f1 = fopen("barbar.in", "r");
FILE *f2 = fopen("barbar.out", "w");

int a[DIM][DIM], prp[DIM][DIM], c[2][DIM*DIM];
int n, m;
int i, j, d;
char x, end;
int ucoz, pcoz, ubin, pbin, dist;
int ic, jc, iv, jv, ist, jst, ifin, jfin;

int main(){
	
	fscanf(f1, "%d %d\n", &n, &m);
	for (i=1; i<=n; i++, fscanf(f1, "\n"))
		for (j=1; j<=m; j++){
			prp[i][j] = -1;
			
			fscanf(f1, "%c", &x);			
			switch (x){
				case 'D':
					c[0][++ucoz] = i;
					c[1][ucoz] = j;
					prp[i][j] = 0;
					break;
				case 'I':
					ist = i;
					jst = j;
					break;
				case 'O':
					ifin = i;
					jfin = j;
					break;
				case '*':
					a[i][j] = 1;
					prp[i][j] = -2;
					break;
			}					
		}	
	
	pcoz = 1;
	while (pcoz <= ucoz){
		ic = c[0][pcoz];
		jc = c[1][pcoz];
		
		for (d=0; d<=3; d++){
			iv = ic + di[d];
			jv = jc + dj[d];
			
			if(prp[iv][jv] == -1){
				c[0][++ucoz] = iv;
				c[1][ucoz] = jv;
				prp[iv][jv] = prp[ic][jc] + 1;			
			}
		}		
		pcoz++;
	}
	
	pbin = 1, ubin = n * m;
	a[ist][jst] = 1;
	while (pbin <= ubin){
		dist = pbin + (ubin - pbin) / 2;
		
		for (i=1; i<=n; i++)
			for (j=1; j<=m; j++)
				if (a[iv][jv] == -1)
					a[iv][jv] = 0;
		
		c[0][1] = ist, c[1][1] = jst; 
		pcoz = 1, ucoz = 1;
		while (pcoz <= ucoz && !end){
			ic = c[0][pcoz];
			jc = c[1][pcoz];
			
			for (d=0; d<=3; d++){
				iv = ic + di[d];
				jv = jc + dj[d];
				
				if (iv>0 && jv>0 && iv<=n && jv<=m && dist <= prp[iv][jv] && !a[iv][jv]){
					c[0][++ucoz] = iv;
					c[1][ucoz] = jv;
					a[iv][jv] = -1;
					
					if(iv == ifin && jv == jfin){
						end = 1;
						break;
					}
				}				
			}			
			pcoz++;
		}
		
		if (end)
			pbin = dist + 1;
		else
			ubin = dist - 1;
	}
	if (ubin != n * m + 1)
		fprintf (f2, "%d", ubin);
	else
		fprintf (f2, "-1");
	fclose(f1);
	fclose(f2);
	
	return 0;
}