Pagini recente » Cod sursa (job #1859964) | Cod sursa (job #72641) | Cod sursa (job #2034663) | Cod sursa (job #108548) | Cod sursa (job #1382969)
#include <fstream>
#include <queue>
#define nmax 1005
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n,m,p,a[nmax][nmax],g,v[nmax*nmax],dp[nmax][nmax],pa,pb,l,r;
char st[nmax][nmax];
bool ok[nmax*nmax],f[nmax*nmax];
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
queue<int>q,Q;
struct Coord{
int x,y;
};
Coord s[nmax*nmax];
inline bool Valid(int i,int j){
if(i < 1 || j < 1|| i > n || j > m)return false;
return true;
}
inline void CREATE(){
int b,x,y,t;
while(!q.empty()){
b=q.front();
ok[b]=0;
q.pop();
for(int i=0;i<4;i++){
x=s[b].x+dx[i];
y=s[b].y+dy[i];
t=m*(x-1)+y;
if(Valid(x,y) && (!a[x][y] || a[x][y] > a[s[b].x][s[b].y]+1)&&st[x][y]!='D'&&st[x][y]!='*'){
a[x][y]=a[s[b].x][s[b].y]+1;
if(!ok[t]){
ok[t]=1;
q.push(t);
}
}
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
r=max(r,a[i][j]);
}
inline bool BFS(int lg){
int i,j,b,x,y,sa,sb;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
if(dp[i][j]!=-1)dp[i][j]=-2;
Q.push(g);
f[g]=1;
dp[s[g].x][s[g].y]=0;
while(!Q.empty()){
b=Q.front();
f[b]=0;
Q.pop();
sa=s[b].x;sb=s[b].y;
for(i=0;i<4;i++){
x=sa+dx[i];
y=sb+dy[i];
j=m*(x-1)+y;
if(Valid(x,y)&& (dp[x][y] > dp[sa][sb]+1||dp[x][y]==-2)&&st[x][y]!='*'&&a[x][y] >= lg){
dp[x][y]=dp[sa][sb]+1;
if(!f[j]){
Q.push(j);
f[j]=1;
}
}
}
}
if(dp[pa][pb]>0&&a[s[g].x][s[g].y]>=lg)
return 1;
return 0;
}
int main(){
int i,j,mij,x;
fin >> n >> m;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{fin>>st[i][j];
if(st[i][j]=='I')g=p+1;
else if(st[i][j]=='*')dp[i][j]=-1;
s[++p].x=i;s[p].y=j;
if(st[i][j]=='D') {q.push(p);ok[p]=1;}
if(st[i][j]=='O'){pa=i;pb=j;}
}
fin.close();
CREATE();
j=-1;
l=0;
while(l<=r){
mij=(l+r)/2;
x=BFS(mij);
if(!x)r=mij-1;
else {j=mij;l=mij+1;}
}
fout<<j;
fout.close();
return 0;
}