Cod sursa(job #1453340)

Utilizator daniel.grosuDaniel Grosu daniel.grosu Data 23 iunie 2015 12:32:31
Problema Barbar Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.77 kb
#define REP(a,b) for(int a=0; a<(b); ++a)
#define FWD(a,b,c) for(int a=(b); a<(c); ++a)
#define FWDS(a,b,c,d) for(int a=(b); a<(c); a+=d)
#define BCK(a,b,c) for(int a=(b); a>(c); --a)
#define ALL(a) (a).begin(), (a).end()
#define SIZE(a) ((int)(a).size())
#define VAR(x) #x ": " << x << " "
#define FILL(x,y) memset(x,y,sizeof(x))
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#define x first
#define y second
#define st first
#define nd second
#define pb push_back
#define nleft (n<<1)
#define nright (nleft+1)
 
#include<vector>
#include<queue>
 
using namespace std;
#include<fstream>
ifstream cin("barbar.in");
ofstream cout("barbar.out");
 
const int NMAX = 1005;
typedef long long LL;
typedef pair<int, int> PII;
typedef long double K;
typedef pair<K, K> PKK;
typedef vector<int> VI;
struct Point{int x,y;};
 
const int dx[] = {0,0,-1,1}; //1,1,-1,1};
const int dy[] = {-1,1,0,0}; //1,-1,1,-1};

int n,k,i,r,c,logN;

int T[NMAX][NMAX];
int viz[NMAX][NMAX];

Point startp, endp;

Point D[NMAX*NMAX]; // Dragoni
int d; // nr de dragoni

bool check(int val)
{
	bool q;
	queue<Point> Q;
	Q.push(startp);
	while(!Q.empty())
	{
		int fx=Q.front().x;
		int fy=Q.front().y;
		for(i=0; i<4; ++i)
		{
			Point a=Q.front();
			a.x+=dx[i];
			a.y+=dy[i];
			
			if(a.x==endp.x && a.y==endp.y) q=true;
			if(a.x>=0 && a.x<c && a.y>=0 && a.y<r && T[a.x][a.y]>=val && viz[a.x][a.y]!=val){
				Q.push(a); 
				viz[a.x][a.y]=val;
			}
		}
		
		Q.pop();
	}
	return q;
}

void build_matrix()
{
	queue<Point> Q;
	REP(i,d)
		Q.push(D[i]);
	
	while(!Q.empty())
	{
		int fx=Q.front().x;
		int fy=Q.front().y;
		for(i=0; i<4; ++i)
		{
			Point a=Q.front();
			a.x+=dx[i];
			a.y+=dy[i];
			if(a.x>=0 && a.x<c && a.y>=0 &&a.y<r && T[a.x][a.y]==0)
			{
				if(T[fx][fy]==-1)
					T[a.x][a.y]=1;
				else
					T[a.x][a.y]=T[fx][fy]+1;
				Q.push(a);
			}
		}
		Q.pop();
	}
}


int upper_bound()
{
    int i=0, step;
    for(step=logN, i=0; step; step>>=1)
        if(i+step<=r*c && check(i+step))
        {
            i+=step;
		}
    return i;
}

int main() {
	cin>>r>>c;
	
	REP(i,r)
		REP(j,c)
		{
			char a;
			cin>>a;
			switch(a)
			{
				case '.':
					T[i][j]=0;
				break;
				case '*':
					T[i][j]=-1;
				break;
				case 'I':
					startp.x=i;
					startp.y=j;
					T[i][j]=-1;
				break;
				case 'O':
					endp.x=i;
					endp.y=j;
					T[i][j]=-1;
				break;
				case 'D':
					Point a;
					a.x=i;
					a.y=j;
					D[d++]=a;
					T[i][j]=-1;
				break;
					
			}
		}
    
    build_matrix();
    
    
    
	
    for(logN=1;logN<=r*c;logN<<=1);
    i=upper_bound()-1;
	if(i)
		cout<<i;
	else
		cout<<-1;
    
    return 0;
}