Cod sursa(job #2026685)

Utilizator cella.florescuCella Florescu cella.florescu Data 24 septembrie 2017 21:16:50
Problema Barbar Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.16 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e3;
typedef pair <int, int> PII;

queue <PII> q;
PII start, finish;
int dist[MAXN + 2][MAXN + 2], dirl[] = {-1, 0, 1, 0}, dirc[] = {0, 1, 0, -1};
char mat[MAXN + 2][MAXN + 2], seen[MAXN + 2][MAXN + 2];

inline int solve(int n, int m, int mind) {
  memset(seen, 0, sizeof seen);
  seen[start.first][start.second] = 1;
  q.push(start);
  while (q.empty() == false) {
    auto pos = q.front();
    q.pop();
    for (int i = 0; i < 4; ++i)
      if (seen[pos.first + dirl[i]][pos.second + dirc[i]] == 0 && dist[pos.first + dirl[i]][pos.second + dirc[i]] >= mind) {
        seen[pos.first + dirl[i]][pos.second + dirc[i]] = 1;
        q.push({pos.first + dirl[i], pos.second + dirc[i]});
      }
  }
  return seen[finish.first][finish.second];
}

int main()
{
    int n, m;
    ifstream fin("barbar.in");
    fin >> n >> m;
    for (int i = 1; i <= n; ++i)
      for (int j = 1; j <= m; ++j) {
        fin >> mat[i][j];
        switch (mat[i][j]) {
          case 'D':
            q.push({i, j});
            dist[i][j] = 1;
            break;
          case 'I':
            start = {i, j};
            mat[i][j] = '.';
            break;
          case 'O':
            finish = {i, j};
            mat[i][j] = '.';
            break;
        }
      }
    fin.close();
    while (q.empty() == false) {
      auto drg = q.front();
      q.pop();
      for (int i = 0; i < 4; ++i)
        if (mat[drg.first + dirl[i]][drg.second + dirc[i]] == '.' && dist[drg.first + dirl[i]][drg.second + dirc[i]] == 0) {
          dist[drg.first + dirl[i]][drg.second + dirc[i]] = dist[drg.first][drg.second] + 1;
          q.push({drg.first + dirl[i], drg.second + dirc[i]});
        }
    }
    for (int i = 0; i <= n + 1; ++i)
      for (int j = 0; j <= m + 1; ++j)
        dist[i][j] = dist[i][j] == 0 ? INT_MIN : dist[i][j] - 1;
    int ans = 0;
    for (int step = (1 << 19); step > 0; step >>= 1)
      if (solve(n, m, ans + step))
        ans += step;
    if (solve(n, m, 0) == 0)
      ans = -1;
    ofstream fout("barbar.out");
    fout << ans;
    fout.close();
    return 0;
}