Cod sursa(job #2627295)

Utilizator victorzarzuZarzu Victor victorzarzu Data 10 iunie 2020 13:00:18
Problema Barbar Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.95 kb
#include <bits/stdc++.h>
#define perete 0x3f3f3f3f 

using namespace std;
ifstream f("barbar.in");
ofstream g("barbar.out");
int n, m, xstart, ystart, xfinish, yfinish;
char ch;
int a[1005][1005], b[1005][1005];
bool viz[1005][1005], ok;

struct node 
{
  int x, y;
};
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, 1, -1};
queue<node> q;

void Read()
{
  f>>n>>m;
  for(int i = 1;i <= n;++i)
    for(int j = 1;j <= m;++j)
      {
        f>>ch;
        b[i][j] = perete;
        if(ch == '*')
          a[i][j] = perete;
        else if(ch == 'D')
          q.push({i, j}), b[i][j] = 0;
        else if(ch == 'I')
          xstart = i, ystart = j;
        else if(ch == 'O')
          xfinish = i, yfinish = j;
      }
}

void Prepare()
{
  int x_new, y_new;
  while(!q.empty())
  {
    node curr = q.front();
    q.pop();

    for(int i = 0;i < 4;++i)
      {
        x_new = curr.x + dx[i];
        y_new = curr.y + dy[i];

        if(x_new < 1 || y_new < 1 || x_new > n || y_new > m || a[x_new][y_new] == perete)
          continue;

        if(b[x_new][y_new] > b[curr.x][curr.y] + 1)
          q.push({x_new, y_new}), b[x_new][y_new] = b[curr.x][curr.y] + 1;
      }
  }
}

void check(int x, int y, int val)
{
  int x_new, y_new;
  if(b[x][y] < val || viz[x][y] || a[x][y] == perete)
    return;
  if(x == xfinish && y == yfinish)
    ok = true;
  if(ok)
    return;
  viz[x][y] = true;
  for(int i = 0;i < 4;++i)
    {
      x_new = dx[i] + x;
      y_new = dy[i] + y;
      
      if(x_new < 1 || y_new < 1 || x_new > n || y_new > m)
        continue;
      check(x_new, y_new, val);
    }
}

void Solve()
{
  int low = 0, high = n * m, rez, mid;
  while(low <= high)
  {
    mid = (low + high) / 2;
    ok = false;

    for(int i = 1;i <= n;++i)
      for(int j = 1;j <= m;++j)
        viz[i][j] = false;

    check(xstart, ystart, mid);
    if(ok)
      rez = mid, low = mid + 1;
    else
      high = mid - 1;
  }
  g<<rez;
}

int main()
{
  Read();
  Prepare();
  Solve();
  return 0;
}