Pagini recente » Cod sursa (job #325907) | Cod sursa (job #2195117) | Cod sursa (job #2772732) | Cod sursa (job #478195) | Cod sursa (job #1847626)
#include <fstream>
#include <deque>
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
struct pct {
int x, y;
};
pct drg[8005];
int nd, ix, iy, ox, oy;
const int f_mare = 1e8;
char s[1005][1005];
int dist[1005][1005];
int ddr[1005][1005];
int dx[] = {-1,0,1,0}, dy[] = {0,1,0,-1};
int i, j, n, m;
inline void reset() {
int i, j;
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
if (s[i][j] == 'D' || s[i][j] == '*')
dist[i][j] = -1;
else dist[i][j] = f_mare;
}
inline bool inauntru (const int &x, const int &y) {
return x >= 1 && y >= 1 && x <= n && y <= m;
}
deque <pct> c1;
inline void bfd(const int &X, const int &Y) {
int x, y, xx,yy;
c1.clear();
c1.push_back({X, Y});
dist[X][Y] = 0;
while (c1.empty() == 0) {
x = c1.front().x;
y = c1.front().y;
c1.pop_front();
for (i = 0; i < 4; i++) {
xx = x+dx[i];
yy = y+dy[i];
if (dist[xx][yy] > dist[x][y]+1 && inauntru(xx, yy)) {
dist[xx][yy] = dist[x][y]+1;
c1.push_back({xx, yy});
}
}
}
}
inline bool bf(const int LIM) {
int x, y, xx, yy;
c1.clear();
c1.push_back({ix, iy});
dist[ix][iy] = 0;
while (c1.empty() == 0) {
x = c1.front().x;
y = c1.front().y;
c1.pop_front();
for (i = 0; i < 4; i++) {
xx = x+dx[i];
yy = y+dy[i];
if (dist[xx][yy] > dist[x][y]+1 && inauntru(xx, yy) && ddr[xx][yy] >= LIM) {
dist[xx][yy] = dist[x][y]+1;
if (xx == ox && yy == oy)
return 1;
c1.push_back({xx, yy});
}
}
}
return 0;
}
int main() {
f >> n >> m; f.get();
for (i = 1; i <= n; i++) {
f.getline(s[i]+1, sizeof(s[i]));
for (j = 1; j <= m; j++) {
if (s[i][j] == 'I')
ix = i, iy = j;
if (s[i][j] == 'D')
drg[++nd] = {i, j};
if (s[i][j] == 'O')
ox = i, oy = j;
}
}
int w;
reset();
bfd(drg[1].x, drg[1].y);
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
ddr[i][j] = dist[i][j];
for (w = 2; w <= nd; w++) {
reset();
bfd(drg[w].x, drg[w].y);
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++)
ddr[i][j] = min(ddr[i][j], dist[i][j]);
}
int p = 1;
while (p < n)
p *= 2;
j = 0;
while (p) {
reset();
if (bf(j+p))
j += p;
p /= 2;
}
g << j;
return 0;
}