Problem p00481 (C++) — buggy submission, verdict: Memory Limit Exceeded

/**
 * File    : JOI_2010_cheese.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-3-8 21:40:42
 * Powered by Visual Studio Code
 */

#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <iomanip> // << fixed << setprecision(xxx)
#include <iostream>
#include <map> // if (M.find(key) != M.end()) { }
#include <queue>
#include <random> // random_device rd; mt19937 mt(rd());
#include <set>
#include <stack>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <tuple>
#include <vector>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
const int infty = 1000000007;

typedef tuple<int, int> point;

int H, W, N;
string S[1010];
int d[1010][1010];
point P[20];
queue<point> Q[20];

bool valid(int x, int y) {
  return (0 <= x && x < H && 0 <= y && y < W && S[x][y] != 'X');
}

int main() {
  cin >> H >> W >> N;
  for (auto i = 0; i < H; i++) {
    cin >> S[i];
  }
  for (auto i = 0; i < H; i++) {
    for (auto j = 0; j < W; j++) {
      if (S[i][j] == 'S') {
        P[0] = point(i, j);
      }
      int t = S[i][j] - '0';
      if (1 <= t && t <= 9) {
        P[t] = point(i, j);
      }
    }
  }
  int ans = 0;
  for (auto i = 0; i < N; i++) {
    fill(&d[0][0], &d[0][0] + 1010 * 1010, infty);
    d[get<0>(P[i])][get<1>(P[i])] = 0;
    Q[i].push(P[i]);
    while (!Q[i].empty()) {
      point p = Q[i].front();
      Q[i].pop();
      if (p == P[i + 1]) {
        ans += d[get<0>(p)][get<1>(p)];
#if DEBUG == 1
        cerr << "d[" << get<0>(p) << "][" << get<1>(p)
             << "] = " << d[get<0>(p)][get<1>(p)] << endl;
#endif
        break;
      }
      for (auto k = 0; k < 4; k++) {
        int nx = get<0>(p) + dx[k];
        int ny = get<1>(p) + dy[k];
        if (valid(nx, ny) && d[nx][ny] == infty) {
          d[nx][ny] = d[get<0>(p)][get<1>(p)] + 1;
          Q[i].push(point(nx, ny));
        }
      }
    }
  }
  cout << ans << endl;
}


Error: MLE

Fixed submission:

#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <complex>
#include <iomanip> // << fixed << setprecision(xxx)
#include <iostream>
#include <map> // if (M.find(key) != M.end()) { }
#include <queue>
#include <set> // S.insert(M);
#include <stack>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <tuple>  // get<n>(xxx)
#include <vector>
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
#include <random>  // random_device rd; mt19937 mt(rd());
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

class UnionFind {
public:
  int N;
  int *root;
  int *rank;

  UnionFind(int n) : N(n) {
    root = new int[N];
    rank = new int[N];
    for (auto i = 0; i < N; ++i) {
      root[i] = i;
      rank[i] = 0;
    }
  }

  ~UnionFind() {
    delete[] root;
    delete[] rank;
  }

  int find(int x) {
    if (root[x] == x)
      return x;
    return root[x] = find(root[x]);
  }

  void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y)
      return;
    if (rank[x] < rank[y]) {
      root[x] = y;
    } else {
      root[y] = x;
      if (rank[x] == rank[y])
        ++(rank[x]);
    }
  }

  bool same(int x, int y) { return (find(x) == find(y)); }
};

class Edge {
public:
  int src, dst;
  ll cost;
  Edge(int s, int d, ll c) : src(s), dst(d), cost(c) {}
  friend bool operator<(const Edge &x, const Edge &y) {
    return x.cost < y.cost;
  }
  friend bool operator>(const Edge &x, const Edge &y) {
    return x.cost > y.cost;
  }
};

typedef Edge State;

class Graph {
public:
  static const ll infty = 100000000000000000;
  int N;
  vector<Edge> *V;
  vector<Edge> edges;
  // dfs
  vector<int> dfs_start;
  int *dfs_visited;
  int *dfs_from;
  int dfs_time;
  int *dfs_time_d;
  int *dfs_time_f;
  // dfs ??§ ??£?????????????±???????
  int *component;
  vector<vector<int>> c_components;
  // bfs
  vector<int> bfs_start;
  int *bfs_visited;
  int *bfs_from;
  ll *bfs_dist;
  // kruskal
  ll kruskal_cost;
  vector<Edge> *kruskal_V;
  vector<Edge> kruskal_W;
  // bellman_ford, dijkstra
  set<int> sh_start;
  ll **sh_dist;
  int **sh_prev;

  Graph(int n) : N(n), dfs_time(0), kruskal_cost(-1) {
    V = new vector<Edge>[N];
    component = new int[N];
    dfs_visited = new int[N];
    fill(dfs_visited, dfs_visited + N, 0);
    dfs_from = new int[N];
    dfs_time_d = new int[N];
    dfs_time_f = new int[N];
    bfs_visited = new int[N];
    fill(bfs_visited, bfs_visited + N, 0);
    bfs_from = new int[N];
    bfs_dist = new ll[N];
    kruskal_V = new vector<Edge>[N];
    sh_dist = new ll *[N];
    sh_prev = new int *[N];
  }
  ~Graph() {
    delete[] V;
    delete[] component;
    delete[] dfs_visited;
    delete[] dfs_from;
    delete[] dfs_time_d;
    delete[] dfs_time_f;
    delete[] bfs_visited;
    delete[] bfs_from;
    delete[] bfs_dist;
    delete[] kruskal_V;
    for (auto x : sh_start) {
      delete[] sh_dist[x];
      delete[] sh_prev[x];
    }
    delete[] sh_dist;
    delete[] sh_prev;
  }

  void add_edge(int src, int dst, ll cost = 1) {
    Edge e(src, dst, cost);
    V[src].push_back(e);
    edges.push_back(e);
  }

  vector<int> dfs(int start) {
    vector<int> ans;
    stack<State> S;
    S.push(State(-1, start, 0));
    dfs_start.push_back(start);
    while (!S.empty()) {
      State s = S.top();
      S.pop();
      if (dfs_visited[s.dst] == 0) {
        dfs_visited[s.dst] = 1;
        dfs_time_d[s.dst] = dfs_time++;
        dfs_from[s.dst] = s.src;
        component[s.dst] = start;
        ans.push_back(s.dst);
        S.push(s);
        for (auto x : V[s.dst]) {
          if (dfs_visited[x.dst] == 0) {
            S.push(State(s.dst, x.dst, s.cost + x.cost));
          }
        }
      } else if (dfs_visited[s.dst] == 1) {
        dfs_visited[s.dst] = 2;
        dfs_time_f[s.dst] = dfs_time++;
      }
    }
    return ans;
  }

  void make_c_components() {
    for (auto i = 0; i < N; ++i) {
      if (dfs_visited[i] > 0)
        continue;
      c_components.push_back(dfs(i));
    }
  }

  bool is_connected(int s, int t) {
    if (dfs_visited[s] == 0 || dfs_visited[t] == 0) {
      make_c_components();
    }
    return (component[s] == component[t]);
  }

  void bfs() {
    assert(!bfs_start.empty());
    queue<State> Q;
    for (auto x : bfs_start) {
      Q.push(State(-1, x, 0));
    }
    while (!Q.empty()) {
      State s = Q.front();
      Q.pop();
      if (bfs_visited[s.dst] == 0) {
        bfs_visited[s.dst] = 1;
        bfs_from[s.dst] = s.src;
        bfs_dist[s.dst] = s.cost;
        for (auto x : V[s.dst]) {
          if (bfs_visited[x.dst] == 0) {
            Q.push(State(s.dst, x.dst, s.cost + x.cost));
          }
        }
      }
    }
  }

  int kruskal() {
    if (kruskal_cost != -1)
      return kruskal_cost;
    sort(edges.begin(), edges.end());
    UnionFind u(N);
    int kruskal_cost = 0;
    for (auto e : edges) {
      if (!u.same(e.src, e.dst)) {
        kruskal_V[e.src].push_back(e);
        kruskal_W.push_back(e);
        u.unite(e.src, e.dst);
        kruskal_cost += e.cost;
      }
    }
    return kruskal_cost;
  }

  void new_sh_dist(int i) {
    if (sh_start.find(i) == sh_start.end()) {
      sh_dist[i] = new ll[N];
      sh_prev[i] = new int[N];
      sh_start.insert(i);
    }
  }

  void bellman_ford(int s) {
    new_sh_dist(s);
    for (auto i = 0; i < N; ++i) {
      sh_dist[s][i] = infty;
    }
    sh_dist[s][s] = 0;
    sh_prev[s][s] = -1;
    while (true) {
      bool update = false;
      for (auto e : edges) {
        if (sh_dist[s][e.src] != infty &&
            sh_dist[s][e.dst] > sh_dist[s][e.src] + e.cost) {
          sh_dist[s][e.dst] = sh_dist[s][e.src] + e.cost;
          sh_prev[s][e.dst] = e.src;
          update = true;
        }
      }
      if (!update)
        break;
    }
  }

  void dijkstra(int s) {
    new_sh_dist(s);
    for (auto i = 0; i < N; ++i) {
      sh_dist[s][i] = infty;
    }
    priority_queue<Edge, vector<Edge>, greater<Edge>> Q;
    Q.push(State(-1, s, 0));
    while (!Q.empty()) {
      State now = Q.top();
      Q.pop();
      if (sh_dist[s][now.dst] == infty) {
        sh_dist[s][now.dst] = now.cost;
        sh_prev[s][now.dst] = now.src;
        for (auto e : V[now.dst]) {
          if (sh_dist[s][e.dst] == infty) {
            Q.push(State(e.src, e.dst, e.cost + now.cost));
          }
        }
      }
    }
  }

  vector<int> get_shortest_path(int s, int t) {
    vector<int> path;
    for (; t != -1; t = sh_prev[s][t])
      path.push_back(t);
    reverse(path.begin(), path.end());
    return path;
  }
};

class Grid : public Graph {
public:
  int H;
  int W;
  static const int dx[], dy[];
  typedef tuple<int, int> point;

  Grid(int h, int w) : Graph(h * w), H(h), W(w) {}
  ~Grid() {}

  bool valid(int x, int y) { return (0 <= x && x < H && 0 <= y && y < W); }
  bool valid(point p) { return valid(get<0>(p), get<1>(p)); }

  int point_to_int(int x, int y) { return x * W + y; }
  int point_to_int(point p) { return point_to_int(get<0>(p), get<1>(p)); }

  static bool dammy_true(int x, int y, int z, int w) { return true; }
  static int dammy_one(int x, int y, int z, int w) { return 1; }

  void make_grid_graph(bool func(int, int, int, int) = dammy_true,
                       int func2(int, int, int, int) = dammy_one) {
    for (auto i = 0; i < H; ++i) {
      for (auto j = 0; j < W; ++j) {
        for (auto k = 0; k < 4; ++k) {
          int x = i + dx[k];
          int y = j + dy[k];
          if (valid(x, y) && func(i, j, x, y)) {
            add_edge(point_to_int(i, j), point_to_int(x, y), func2(i, j, x, y));
          }
        }
      }
    }
  }
};

const int Grid::dx[] = {1, 0, -1, 0};
const int Grid::dy[] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int H, W, N;
string S[1010];

bool can(int x, int y, int z, int w) { return (S[z][w] != 'X'); }

int main() {
  cin >> H >> W >> N;
  Grid g(H, W);
  for (auto i = 0; i < H; ++i) {
    cin >> S[i];
  }
  g.make_grid_graph(can);
  tuple<int, int> P[10];
  for (auto i = 0; i < H; ++i) {
    for (auto j = 0; j < W; ++j) {
      int num = (S[i][j] - '0');
      if (1 <= num && num <= N) {
        P[num] = make_tuple(i, j);
      }
      if (S[i][j] == 'S') {
        P[0] = make_tuple(i, j);
      }
    }
  }
  int ans = 0;
  for (auto i = 0; i < N; ++i) {
    fill(g.bfs_visited, g.bfs_visited + g.N, 0);
    g.bfs_start.clear();
    g.bfs_start.push_back(g.point_to_int(P[i]));
    g.bfs();
    ans += g.bfs_dist[g.point_to_int(P[i + 1])];
  }
  cout << ans << endl;
}