Cod sursa(job #2958434)

Utilizator LukyenDracea Lucian Lukyen Data 26 decembrie 2022 16:41:36
Problema Barbar Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.44 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("cod.in");
ofstream fout("cod.out");
const short vec_len = 1001;

struct pos
{
  short l;
  short c;
};

short n, m;
vector<vector<short>> dmap(vec_len, vector<short>(vec_len, __INT8_MAX__));
short dirl[] = {-1, 0, 1, 0}, dirc[] = {0, 1, 0, -1};

pos tstart, texit;
queue<pos> drag;

bool check(short l, short c)
{
  if (l < 1 || l > n)
    return false;

  if (c < 1 || c > m)
    return false;

  if (dmap[l][c] == -1)
    return false;

  return true;
}

void dragLee()
{
  vector<vector<bool>> vis(vec_len, vector<bool>(vec_len, false));
  while (!drag.empty())
  {
    pos curr = drag.front();
    vis[curr.l][curr.c] = true;
    drag.pop();

    short nl = curr.l, nc = curr.c;
    for (short i = 0; i < 4; i++)
    {
      nl = curr.l + dirl[i];
      nc = curr.c + dirc[i];

      if (check(nl, nc) && !vis[nl][nc])
      {
        dmap[nl][nc] = min(dmap[nl][nc], (short)(dmap[curr.l][curr.c] + 1));
        drag.push(pos{nl, nc});
      }
    }
  }
}

void pathLee()
{
  vector<vector<bool>> vis(vec_len, vector<bool>(vec_len, false));
  short maxx = __INT8_MAX__;

  priority_queue<tuple<short, short, short>> path;
  path.push(make_tuple(dmap[tstart.l][tstart.c], tstart.l, tstart.c));

  while (!path.empty())
  {
    tuple<short, short, short> curr = path.top();
    path.pop();
    maxx = min(maxx, get<0>(curr));

    if (get<1>(curr) == texit.l && get<2>(curr) == texit.c)
      break;

    short nl, nc;
    for (short i = 0; i < 4; i++)
    {
      nl = get<1>(curr) + dirl[i];
      nc = get<2>(curr) + dirc[i];

      if (check(nl, nc) && !vis[nl][nc])
      {
        path.push(make_tuple(dmap[nl][nc], nl, nc));
        vis[nl][nc] = true;
      }
    }
  }

  fout << maxx;
}

void prshort()
{
  for (short i = 1; i <= n; i++)
  {
    for (short j = 1; j <= m; j++)
      cout << dmap[i][j] << " ";
    cout << "\n";
  }
}

int main()
{
  fin.tie(NULL);
  fout.tie(NULL);
  ios::sync_with_stdio(false);

  fin >> n >> m;

  char x;
  for (short i = 1; i <= n; i++)
    for (short j = 1; j <= m; j++)
    {
      fin >> x;
      if (x == 'D')
        drag.push(pos{i, j}), dmap[i][j] = 0;
      else if (x == 'I')
        tstart = pos{i, j};
      else if (x == '*')
        dmap[i][j] = -1;
      else if (x == 'O')
        texit = pos{i, j};
    }

  dragLee();
  pathLee();

  return 0;
}