Problem p02670 (C++) — buggy submission, verdict: Time Limit Exceeded

#include <bits/stdc++.h>
using namespace std;

#define rep(i, s, n) for (int i = (ll)s; i < (ll)n; i++)
#define rrep(i, n, e) for (int i = (ll)n - 1; i >= (ll)e; i--)
#define ll long long
#define ld long double
#define pb push_back
#define eb emplace_back
#define All(x) x.begin(), x.end()
#define Range(x, i, j) x.begin() + i, x.begin() + j
#define lbidx(x, y) lower_bound(x.begin(), x.end(), y) - x.begin()
#define ubidx(x, y) upper_bound(x.begin(), x.end(), y) - x.begin()
#define llbidx(x, y, z)                                                        \\
  lower_bound(x.begin(), x.end(), z) -                                         \\
      lower_bound(x.begin(), x.end(), y) // 二要素間の距離
// #define M_PI 3.14159265358979323846 // CFでは定義しておく必要あり
#define deg2rad(deg) ((((double)deg) / ((double)360) * 2 * M_PI))
#define rad2deg(rad) ((((double)rad) / (double)2 / M_PI) * (double)360)
#define Find(set, element) set.find(element) != set.end()
#define Decimal(x)                                                             \\
  cout << fixed << setprecision(10) << x << endl; // 小数点を10桁まで表示
// debug用
#define PrintVec(x)                                                            \\
  for (auto elementPrintVec : x) {                                             \\
    cout << elementPrintVec << " ";                                            \\
  }                                                                            \\
  cout << "\\n";
#define debug(x) cerr << #x << ": " << (x) << "\\n";
#define endl "\\n"
// gcj print用
#define Case(x) printf("Case #%d: ", x);

typedef pair<int, int> PI;
typedef pair<ll, ll> PLL;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>> vvvi;
typedef vector<ll> vl;
typedef vector<vector<ll>> vvl;
typedef vector<vector<vector<int>>> vvvl;
typedef vector<PI> vpi;
typedef vector<vector<PI>> vvpi;
typedef vector<vector<vector<PI>>> vvvpi;
typedef vector<PLL> vpl;
typedef vector<vector<PLL>> vvpl;
typedef vector<vector<vector<PLL>>> vvvpl;

int POWINT(int x, int n) {
  int ret = 1;
  while (n > 0) {
    if (n & 1)
      ret *= x;
    x *= x;
    n >>= 1;
  }
  return ret;
};

ll POWLL(ll x, int n) {
  ll ret = 1;
  while (n > 0) {
    if (n & 1)
      ret *= x;
    x *= x;
    n >>= 1;
  }
  return ret;
};

template <class T> inline bool chmax(T &a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
};

template <class T> inline bool chmin(T &a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
};

void print() { cout << endl; };

template <class T> void print(vector<T> &vec) {
  for (auto &a : vec) {
    cout << a;
    if (&a != &vec.back())
      cout << " ";
  }
  cout << endl;
};

template <class T> void print(vector<T> &vec, ll k) {
  ll n = vec.size();
  k = min(k, n);
  rep(i, 0, k - 1) cout << vec[i] << " ";
  cout << vec[k - 1] << endl;
};

template <class T> void print(vector<vector<T>> &df) {
  for (auto &vec : df) {
    print(vec);
  }
};

template <class T, class U> void print(pair<T, U> &p) {
  cout << p.first << " " << p.second << "\\n";
};

int dx[4] = {0, 1, 0, -1}; // u, r, d, l
int dy[4] = {-1, 0, 1, 0};

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

  int N;
  cin >> N;
  vector<vector<bool>> grid(N, vector<bool>(N, true));
  int NN = N * N;
  vi A(NN);
  rep(i, 0, NN) {
    cin >> A[i];
    A[i]--;
  }

  vvi dist(N, vi(N));
  rep(i, 0, N) {
    rep(j, 0, N) {
      int d = N - 1;
      chmin(d, N - 1 - i);
      chmin(d, i);
      chmin(d, N - 1 - j);
      chmin(d, j);
      dist[i][j] = d;
    }
  }

  int ans = 0;
  for (int a : A) {
    int x = a % N;
    int y = a / N;
    ans += dist[y][x];
    grid[y][x] = false;
    queue<int> q;
    q.push(a);
    while (!q.empty()) {
      int v = q.front();
      q.pop();
      int vx = v % N;
      int vy = v / N;
      bool vp = grid[vy][vx]; // 人がまだいる
      int vd = dist[vy][vx];
      rep(i, 0, 4) {
        int ux = vx + dx[i];
        int uy = vy + dy[i];
        if (0 <= ux && ux < N && 0 <= uy && uy < N) {
          int u = uy * N + ux;
          int nxtd = vd;
          if (vp)
            nxtd++;

          if (dist[uy][ux] > nxtd) {
            dist[uy][ux] = nxtd;
            q.push(u);
          }
        }
      }
    }
  }

  cout << ans << endl;

  return 0;
};


Error: TLE

Fixed submission:

#include <bits/stdc++.h>
using namespace std;

#define rep(i, s, n) for (int i = (ll)s; i < (ll)n; i++)
#define rrep(i, n, e) for (int i = (ll)n - 1; i >= (ll)e; i--)
#define ll long long
#define ld long double
#define pb push_back
#define eb emplace_back
#define All(x) x.begin(), x.end()
#define Range(x, i, j) x.begin() + i, x.begin() + j
#define lbidx(x, y) lower_bound(x.begin(), x.end(), y) - x.begin()
#define ubidx(x, y) upper_bound(x.begin(), x.end(), y) - x.begin()
#define llbidx(x, y, z)                                                        \\
  lower_bound(x.begin(), x.end(), z) -                                         \\
      lower_bound(x.begin(), x.end(), y) // 二要素間の距離
// #define M_PI 3.14159265358979323846 // CFでは定義しておく必要あり
#define deg2rad(deg) ((((double)deg) / ((double)360) * 2 * M_PI))
#define rad2deg(rad) ((((double)rad) / (double)2 / M_PI) * (double)360)
#define Find(set, element) set.find(element) != set.end()
#define Decimal(x)                                                             \\
  cout << fixed << setprecision(10) << x << endl; // 小数点を10桁まで表示
// debug用
#define PrintVec(x)                                                            \\
  for (auto elementPrintVec : x) {                                             \\
    cout << elementPrintVec << " ";                                            \\
  }                                                                            \\
  cout << "\\n";
#define debug(x) cerr << #x << ": " << (x) << "\\n";
#define endl "\\n"
// gcj print用
#define Case(x) printf("Case #%d: ", x);

typedef pair<int, int> PI;
typedef pair<ll, ll> PLL;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>> vvvi;
typedef vector<ll> vl;
typedef vector<vector<ll>> vvl;
typedef vector<vector<vector<int>>> vvvl;
typedef vector<PI> vpi;
typedef vector<vector<PI>> vvpi;
typedef vector<vector<vector<PI>>> vvvpi;
typedef vector<PLL> vpl;
typedef vector<vector<PLL>> vvpl;
typedef vector<vector<vector<PLL>>> vvvpl;

int POWINT(int x, int n) {
  int ret = 1;
  while (n > 0) {
    if (n & 1)
      ret *= x;
    x *= x;
    n >>= 1;
  }
  return ret;
};

ll POWLL(ll x, int n) {
  ll ret = 1;
  while (n > 0) {
    if (n & 1)
      ret *= x;
    x *= x;
    n >>= 1;
  }
  return ret;
};

template <class T> inline bool chmax(T &a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
};

template <class T> inline bool chmin(T &a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
};

void print() { cout << endl; };

template <class T> void print(vector<T> &vec) {
  for (auto &a : vec) {
    cout << a;
    if (&a != &vec.back())
      cout << " ";
  }
  cout << endl;
};

template <class T> void print(vector<T> &vec, ll k) {
  ll n = vec.size();
  k = min(k, n);
  rep(i, 0, k - 1) cout << vec[i] << " ";
  cout << vec[k - 1] << endl;
};

template <class T> void print(vector<vector<T>> &df) {
  for (auto &vec : df) {
    print(vec);
  }
};

template <class T, class U> void print(pair<T, U> &p) {
  cout << p.first << " " << p.second << "\\n";
};

class Dijkstra {
  ll INF = (1ll << 58);
  int WHITE = 0; // 未到達
  int GRAY = 1;  // 到達
  int BLACK = 2; // 探索済み
public:
  int V; // 頂点数
  // <node, cost>
  vector<vector<pair<int, ll>>> graph;
  vector<int> color;
  vector<ll> dist;
  vector<int> parent;

  Dijkstra(int v) : V(v) {
    graph.resize(v);
    color.resize(v);
    dist.resize(v);
    parent.resize(v);
  }

  void add_edge(int from, int to, ll cost) {
    graph[from].pb(make_pair(to, cost));
  }

  void min_path(int s) {
    // <cost, node>
    priority_queue<pair<ll, int>> PQ;

    // 初期化
    for (int i = 0; i < V; i++) {
      dist[i] = INF;
      color[i] = 0;
    }

    dist[s] = 0;
    PQ.push(make_pair(0ll, s));
    color[s] = GRAY;

    while (!PQ.empty()) {
      auto f = PQ.top();
      PQ.pop();
      int u = f.second;
      color[u] = BLACK;

      for (int j = 0; j < graph[u].size(); j++) {
        int v = graph[u][j].first;
        if (color[v] == BLACK)
          continue;
        if (dist[v] > dist[u] + graph[u][j].second) {
          dist[v] = dist[u] + graph[u][j].second;
          parent[v] = u; // 経路を求めるために親ノードを更新
          // priority_queueはデフォルトで大きい値を優先するため-1をかける
          PQ.push(make_pair(dist[v] * (-1ll), v));
          color[v] = GRAY;
        }
      }
    }
  }
};

int dx[4] = {0, 1, 0, -1}; // u, r, d, l
int dy[4] = {-1, 0, 1, 0};

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

  int N;
  cin >> N;
  vvi grid(N, vi(N, 1));
  int NN = N * N;
  vi A(NN);
  rep(i, 0, NN) {
    cin >> A[i];
    A[i]--;
  }

  ll ans = 0;
  rep(i, 0, NN) {
    int a = A[i];
    int ax = a % N;
    int ay = a / N;
    Dijkstra di(NN + 1);

    rep(j, 0, NN) {
      int x = j % N;
      int y = j / N;
      if (x == 0 || x == N - 1 || y == 0 || y == N - 1)
        di.add_edge(j, NN, 0);
      rep(k, 0, 4) {
        int xx = x + dx[k];
        int yy = y + dy[k];
        if (0 <= xx && xx < N && 0 <= yy && yy < N) {
          int nxt = yy * N + xx;
          if (grid[yy][xx]) {
            di.add_edge(j, nxt, 1);
          } else {
            di.add_edge(j, nxt, 0);
          }
        }
      }
    }

    grid[ay][ax] = 0;
    di.min_path(a);
    ans += di.dist[NN];
  }

  cout << ans << endl;

  return 0;
};