Pagini recente » Cod sursa (job #584868) | Cod sursa (job #1698951)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
typedef int matrice[1001][1001];
matrice a;
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
queue < pair <int, int> >coada;
bitset<1001>ef[1001],es[1001];
int n,m,i,j;
int sx,sy,ox,oy;
char c;
int kfl(int x, int y)
{
return x>=1 && x<=n && y>=1 && y<=m && !a[x][y];
}
int kfs(int x, int y)
{
return x>=1 && x<=n && y>=1 && y<=m && !es[x][y];
}
void lee()
{
int i,j,i2,j2,k;
while(!coada.empty())
{
i=coada.front().first;
j=coada.front().second;
coada.pop();
for(k=0;k<4;k++)
{
i2=i+dx[k];
j2=j+dy[k];
if(kfl(i2,j2))
{
a[i2][j2]=1+a[i][j];
coada.push(make_pair(i2,j2));
}
}
}
}
int exd(int v)
{
int i,j,i2,j2,k;
memcpy(es,ef,sizeof(ef));
es[sx][sy]=1;
coada.push(make_pair(sx,sy));
while(!coada.empty())
{
i=coada.front().first;
j=coada.front().second;
coada.pop();
for(k=0;k<4;k++)
{
i2=i+dx[k];
j2=j+dy[k];
if(kfs(i2,j2) && a[i2][j2]-1>=v)
{
es[i2][j2]=1;
coada.push(make_pair(i2,j2));
}
}
}
return es[ox][oy];
}
int solutie()
{
int s=1,d=a[sx][sy]-1,m,best=-1;
while(s<=d)
{
m=s+(d-s)/2;
if(exd(m))
{
best=m;
s=m+1;
}
else d=m-1;
}
return best;
}
void afis(matrice a)
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)cout<<a[i][j]<<" ";
cout<<"\n";
}
cout<<"\n";
}
int main()
{
fin>>n>>m;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
fin>>c;
if(c=='I')sx=i,sy=j;
if(c=='O')ox=i,oy=j;
if(c=='D')coada.push(make_pair(i,j)),ef[i][j]=1,a[i][j]=1;
if(c=='*')ef[i][j]=1;
}
lee();
fout<<solutie()<<"\n";
return 0;
}