Submission #1364050

#TimeUsernameProblemLanguageResultExecution timeMemory
1364050edoMaze (JOI23_ho_t3)C++20
100 / 100
494 ms70816 KiB
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

int r, c, s1, s2, e1, e2, n;

struct S {
  int x, y;
  S() { x = y = 0; }
  S(int x, int y) {
    this->x = x;
    this->y = y;
  }
  vector<S> nxt() {
    vector<S> nx;
    if (x > 0)
      nx.push_back({x - 1, y});
    if (x + 1 < r)
      nx.push_back({x + 1, y});
    if (y > 0)
      nx.push_back({x, y - 1});
    if (y + 1 < c)
      nx.push_back({x, y + 1});
    return nx;
  }
  vector<S> rnxt() {
    vector<S> nx = nxt();
    if (x > 0 && y > 0)
      nx.push_back({x - 1, y - 1});
    if (x > 0 && y + 1 < c)
      nx.push_back({x - 1, y + 1});
    if (x + 1 < r && y > 0)
      nx.push_back({x + 1, y - 1});
    if (x + 1 < r && y + 1 < c)
      nx.push_back({x + 1, y + 1});

    return nx;
  }
};

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  cin >> r >> c >> n >> s1 >> s2 >> e1 >> e2, --s1, --s2, --e1, --e2;

  vector g(r, vector<int>(c));
  for (int i = 0; i < r; ++i) {
    for (int j = 0; j < c; ++j) {
      char t;
      cin >> t;
      g[i][j] = (t != '#');
    }
  }

  const int inf = (1 << 30);

  queue<S> q1, q2;
  S N = {-1, -1};
  q2.push(N);
  q1.push({s1, s2});
  int D = 0;
  vector dist(r, vector<int>(c, inf));
  dist[s1][s2] = 0;
  while (q1.size() || q2.size() > 1) {
    while (q1.size()) {
      S cur = q1.front();
      q1.pop();
      auto nx = cur.nxt();
      for (auto [x, y] : nx) {
        if (g[x][y]) {
          if (dist[x][y] == inf) {
            dist[x][y] = dist[cur.x][cur.y];
            q1.push({x, y});
          }
        } else {
          if (dist[x][y] == inf) {
            q2.push({x, y});
            dist[x][y] = dist[cur.x][cur.y] + 1;
          }
        }
      }
    }
    while (q2.size() > 1) {
      if (D == n) {
        D = 0;
        while (q2.size() && ~q2.front().x) {
          q1.push(q2.front());
          q2.pop();
        }
        break;
      }
      S cur = q2.front();
      q2.pop();
      if (!~cur.x) {
        D++;
        q2.push(N);
        continue;
      }
      auto nx = cur.rnxt();
      for (auto [x, y] : nx) {
        if (dist[x][y] == inf) {
          dist[x][y] = dist[cur.x][cur.y];
          q2.push({x, y});
        }
      }
    }
  }

  cout << dist[e1][e2];

  return 0;
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...