Pagini recente » Cod sursa (job #3343161) | Cod sursa (job #3340994) | Cod sursa (job #3349476) | Cod sursa (job #3333540)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
int R, C, si, sj, fi, fj;
int mat[1005][1005], v[1005][1005];
int di[] = {-1, 1, 0, 0};
int dj[] = {0, 0, -1, 1};
queue<pair<pair<int, int>, int>> dgq;
queue<pair<int, int>> q;
void bfs_dragoni(){
while (!dgq.empty()) {
pair<pair<int, int>, int> curr = dgq.front();
dgq.pop();
for (int t = 0; t < 4; t++) {
int ni = curr.first.first + di[t];
int nj = curr.first.second + dj[t];
if (ni >= 1 && ni <= R && nj >= 1 && nj <= C && mat[ni][nj] == INT_MAX) {
mat[ni][nj] = curr.second + 1;
dgq.push({{ni, nj}, curr.second + 1});
}
}
}
}
bool bfs_paftenie(int k){
if(mat[si][sj] < k) return false;
for(int i = 1; i <= R; i++)
for(int j = 1; j <= C; j++)
v[i][j] = 0;
while(!q.empty()) q.pop();
q.push({si, sj});
v[si][sj] = 1;
while (!q.empty()) {
pair<int, int> curr = q.front();
q.pop();
if(curr.first == fi && curr.second == fj) return true;
for (int t = 0; t < 4; t++) {
int ni = curr.first + di[t];
int nj = curr.second + dj[t];
if (ni >= 1 && ni <= R && nj >= 1 && nj <= C && mat[ni][nj] >= k && v[ni][nj] == 0){
v[ni][nj] = 1;
q.push({ni, nj});
}
}
}
return false;
}
int main(){
f >> R >> C;
for (int i = 1; i <= R; i++) {
for (int j = 1; j <= C; j++) {
char t;
f >> t;
if(t == '*') mat[i][j] = -2;
else if(t == 'D'){
mat[i][j] = 0;
dgq.push({{i, j}, 0});
}
else {
mat[i][j] = INT_MAX;
if(t == 'I'){ si = i; sj = j; }
if(t == '0' || t == 'O'){ fi = i; fj = j; }
}
}
}
bfs_dragoni();
int l = 0, r = R + C, rasp = 0;
while(l <= r){
int m = l + (r - l)/2;
if(bfs_paftenie(m)){
rasp = m;
l = m + 1;
}
else r = m - 1;
}
g << rasp;
return 0;
}