Pagini recente » Cod sursa (job #561892) | Cod sursa (job #2836441) | Cod sursa (job #3155366) | Cod sursa (job #2401915) | Cod sursa (job #1499145)
#include <fstream>
#include <cstring>
#include <queue>
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
const int dl[5] = {0, -1, 0, 1, 0};
const int dc[5] = {0, 0, 1, 0, -1};
char s;
int a[1002][1002],b[1002][1002],i,j,m,n,li,lf,ci,cf,solutie,nn;
struct pozitie {
unsigned char l, c;
}p,pn;
queue <pozitie> q;
void citire()
{
f>>m>>n;
for (i=1;i<=m;i++)
{
for (j=1;j<=n;j++)
{ f>>s;
if (s=='*') {a[i][j]=-1; b[i][j]=-1;}
else if (s=='I') {li=i; ci=j;}
else if(s=='D') {/*a[i][j]=-2;*/ p.l=i; p.c=j; q.push(p); b[i][j]=1;}
else if (s=='O') {lf=i; cf=j;}
}
}
}
void margini()
{
for(i=0;i<=m;i++)
a[i][0]=b[i][0]=a[i][n+1]=b[i][n+1]=-1;
for(j=1;j<=n;j++)
a[0][j]=b[0][j]=a[m+1][j]=b[m+1][j]-1;
}
void drag()
{
int d;
while (!q.empty()) {
p = q.front();
q.pop();
for (d = 1; d <= 4; d++) {
pn.l = p.l + dl[d]; pn.c = p.c + dc[d];
if (b[pn.l][pn.c] == 0) {
b[pn.l][pn.c] = b[p.l][p.c] + 1;
q.push(pn);
}
}
}
}
int cond(int x)
{
int d;
while(!q.empty())
q.pop();
for (i=1;i<=m;i++)
for (j=1;j<=n;j++)
if(a[i][j]>0)
a[i][j]=0;
p.l = li; p.c = ci;
q.push(p);
a[li][ci] = 1;
while (a[lf][cf] == 0 and !q.empty()) {
p = q.front();
q.pop();
for (d = 1; d <= 4; d++) {
pn.l = p.l + dl[d]; pn.c = p.c + dc[d];
if (a[pn.l][pn.c] == 0 and b[pn.l][pn.c]>=x) {
a[pn.l][pn.c] = a[p.l][p.c] + 1;
q.push(pn);
}
}
}
if(a[lf][cf]>0) return 0;
else return 1;
}
int cautare()
{
int step, ans;
for(step = 1; step <= nn; step *= 2);
for(ans = 0; step; step /= 2) {
if(step + ans <= nn && !cond(step + ans)) {
ans += step;
}
}
return ans;
}
int main()
{
citire();
margini();
drag();
if(b[li][ci]>b[lf][cf]) nn=b[lf][cf]; else nn=b[li][ci];
solutie=cautare();
if(solutie>0) g<<solutie-1; else g<<-1;
return 0;
}