Pagini recente » Cod sursa (job #3224537) | Cod sursa (job #706561) | Cod sursa (job #1519902) | Cod sursa (job #1217294) | Cod sursa (job #1228752)
#include<fstream>
#include<queue>
#include<cstring>
#include<vector>
#define punct pair<int,int>
#define x first
#define INF 0x3f3f3f3f
#define y second
#define mp make_pair
#define N 1010
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
int i,j,n,m,li,ls,mij,sol,ok,xx,nxx,yy,nyy,dir;
int d[N][N],b[N][N];
bool a[N][N],viz[N][N];
vector<punct>v;
queue<punct>q;
punct pi,pf;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
char s[1100];
inline bool ein(const int &x,const int &y){
if(x < 1 || y < 1 || x > n || y > n)
return 0;
return 1;
}
inline bool verif(int dist)
{
if(d[pi.x][pi.y] < dist)
return 0;
memset(viz, 0, sizeof(viz));
while(!q.empty()) q.pop();
q.push(pi);
viz[pi.x][pi.y] = 1;
while(!q.empty())
{
xx = q.front().x;
yy = q.front().y;
q.pop();
for(int i = 0; i <= 3; ++i)
{
nxx = xx + dx[i];
nyy = yy + dy[i];
if(ein(nxx, nyy) && !a[nxx][nyy] && d[nxx][nyy] >= dist && !viz[nxx][nyy])
{
viz[nxx][nyy] = 1;
q.push(make_pair(nxx, nyy));
if(nxx == pf.x && nyy == pf.y)
return 1;
}
}
}
return 0;
}
int main()
{
f >> n >> m;
memset(d, INF, sizeof(d));
for(i = 1; i <= n; ++i)
{
f >> (s + 1);
for(j = 1; j <= m; ++j)
{
if(s[j] == '*')
a[i][j] = 1;
if(s[j] == 'I')
pi.x = i,
pi.y = j;
if(s[j] == 'O')
pf.x = i,
pf.y = j;
if(s[j] == 'D')
{
q.push(mp(i, j));
d[i][j] = 0;
}
}
}
while(!q.empty())
{
xx = q.front().x;
yy = q.front().y;
q.pop();
for(dir = 0; dir <= 3; ++dir)
{
nxx = xx + dx[dir];
nyy = yy + dy[dir];
if(ein(nxx, nyy) && !a[nxx][nyy] && d[xx][yy] + 1 < d[nxx][nyy])
{
d[nxx][nyy] = 1 + d[xx][yy];
q.push(mp(nxx,nyy));
}
}
}
for(i = 1; i <= n; ++i)
for(j = 1; j <= m; ++j)
if(!a[i][j])
ls = max(ls, d[i][j]);
li = 0;
sol = -1;
while (li <= ls)
{
mij = (li + ls) >> 1;
if(verif(mij))
sol = mij, li = mij + 1;
else
ls = mij - 1;
}
g << sol << '\n';
return 0;
}