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

#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp> // Common file
// #include <ext/pb_ds/tree_policy.hpp> // Including
// tree_order_statistics_node_update

using namespace std;
// using namespace __gnu_pbds;
// typedef tree<
//         pair<long long, int>, // change type
//         null_type,
//         less<pair<long long, int> >, // change type
//         rb_tree_tag,
//         tree_order_statistics_node_update>
//         ordered_set;

// template<class T> using ordered_set = tree<T, null_type, less<T>,
// rb_tree_tag,tree_order_statistics_node_update>;

vector<string> vec_splitter(string s) {
  s += ',';
  vector<string> res;
  while (!s.empty()) {
    res.push_back(s.substr(0, s.find(',')));
    s = s.substr(s.find(',') + 1);
  }
  return res;
}
void debug_out(vector<string> __attribute__((unused)) args,
               __attribute__((unused)) int idx,
               __attribute__((unused)) int LINE_NUM) {
  cerr << endl;
}
template <typename Head, typename... Tail>
void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) {
  if (idx > 0)
    cerr << ", ";
  else
    cerr << "Line(" << LINE_NUM << ") ";
  stringstream ss;
  ss << H;
  cerr << args[idx] << " = " << ss.str();
  debug_out(args, idx + 1, LINE_NUM, T...);
}
#define debug(...)                                                             \\
  debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)

typedef long long ll;
#define rep(i, start, end) for (int i = start; i < end; ++i)
#define sz(x) (int)((x).size())
#define pb push_back
#define all(x) x.begin(), x.end()
#define clr(d, v) memset(d, v, sizeof(d))
#define pii pair<int, int>
// #define debug(x) cerr << #x << " : " << (x) << " "
const double PI = 3.14159265358979323846;
const double eps = (1e-8);
int isGreater(long double x, long double y) {
  if (abs(x - y) < eps)
    return 0;
  if (x > y)
    return 1;
  return -1;
}

int n;
const int MAX_N = 505;
int dist[MAX_N][MAX_N], isDanger[MAX_N][MAX_N];
int di[] = {-1, 1, 0, 0};
int dj[] = {0, 0, -1, 1};

bool valid(int i, int j) { return i >= 0 && j >= 0 && i < n && j < n; }

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  rep(i, 0, n) {
    rep(j, 0, n) {
      dist[i][j] = min(min(i, n - i - 1), min(j, n - j - 1));
      isDanger[i][j] = 1;
    }
  }

  int ans = 0;
  vector<pair<int, int>> q;
  q.reserve(n * n);
  rep(k, 0, n * n) {
    int x;
    cin >> x;
    --x;
    int i = x / n, j = x % n;
    ans += dist[i][j];
    isDanger[i][j] = 0;
    q.push_back({i, j});
    while (!q.empty()) {
      auto u = q.back();
      int ci = u.first, cj = u.second;
      q.pop_back();
      rep(mv, 0, 4) {
        int ni = ci + di[mv], nj = cj + dj[mv];
        if (valid(ni, nj) && dist[ni][nj] > dist[ci][cj] + isDanger[ci][cj]) {
          dist[ni][nj] = dist[ci][cj] + isDanger[ci][cj];
          q.push_back({ni, nj});
        }
      }
    }
  }
  cout << ans << '\\n';
}

Error: TLE

Fixed submission:

#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp> // Common file
// #include <ext/pb_ds/tree_policy.hpp> // Including
// tree_order_statistics_node_update

using namespace std;
// using namespace __gnu_pbds;
// typedef tree<
//         pair<long long, int>, // change type
//         null_type,
//         less<pair<long long, int> >, // change type
//         rb_tree_tag,
//         tree_order_statistics_node_update>
//         ordered_set;

// template<class T> using ordered_set = tree<T, null_type, less<T>,
// rb_tree_tag,tree_order_statistics_node_update>;

vector<string> vec_splitter(string s) {
  s += ',';
  vector<string> res;
  while (!s.empty()) {
    res.push_back(s.substr(0, s.find(',')));
    s = s.substr(s.find(',') + 1);
  }
  return res;
}
void debug_out(vector<string> __attribute__((unused)) args,
               __attribute__((unused)) int idx,
               __attribute__((unused)) int LINE_NUM) {
  cerr << endl;
}
template <typename Head, typename... Tail>
void debug_out(vector<string> args, int idx, int LINE_NUM, Head H, Tail... T) {
  if (idx > 0)
    cerr << ", ";
  else
    cerr << "Line(" << LINE_NUM << ") ";
  stringstream ss;
  ss << H;
  cerr << args[idx] << " = " << ss.str();
  debug_out(args, idx + 1, LINE_NUM, T...);
}
#define debug(...)                                                             \\
  debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)

typedef long long ll;
#define rep(i, start, end) for (int i = start; i < end; ++i)
#define sz(x) (int)((x).size())
#define pb push_back
#define all(x) x.begin(), x.end()
#define clr(d, v) memset(d, v, sizeof(d))
#define pii pair<int, int>
// #define debug(x) cerr << #x << " : " << (x) << " "
const double PI = 3.14159265358979323846;
const double eps = (1e-8);
int isGreater(long double x, long double y) {
  if (abs(x - y) < eps)
    return 0;
  if (x > y)
    return 1;
  return -1;
}

int n;
const int MAX_N = 505;
int dist[MAX_N][MAX_N], vis[MAX_N][MAX_N], vid, assigned[MAX_N][MAX_N];
bool danger[MAX_N][MAX_N];

int di[] = {-1, 1, 0, 0};
int dj[] = {0, 0, -1, 1};

bool valid(int i, int j) {
  return i >= 0 && j >= 0 && i < n && j < n && vis[i][j] != vid;
}

int stq, enq;
const int qsz = (1 << 20) - 1;
pair<int, int> q[qsz + 1];
pair<int, int> u;
int bfs(int sti, int stj) {
  ++vid;
  dist[sti][stj] = 0;
  assigned[sti][stj] = vid;

  stq = enq = 0;
  q[enq++] = {sti, stj};

  while (stq != enq) {
    while (stq != enq) {
      u = q[stq];
      stq++;
      stq &= qsz;
      int i = u.first, j = u.second;

      if (vis[i][j] == vid)
        continue;

      if (!i || !j || i == n - 1 || j == n - 1)
        return dist[i][j];

      vis[i][j] = vid;

      rep(mv, 0, 4) {
        int ni = i + di[mv], nj = j + dj[mv];
        if (valid(ni, nj)) {
          int w = danger[ni][nj];

          if ((dist[ni][nj] > dist[i][j] + w && assigned[ni][nj] == vid) ||
              assigned[ni][nj] != vid) {
            dist[ni][nj] = dist[i][j] + w;
            assigned[ni][nj] = vid;
            if (w) {
              q[enq++] = {ni, nj};
              enq &= qsz;
            } else {
              stq--;
              stq &= qsz;
              q[stq] = {ni, nj};
              if (!ni || !nj || ni == n - 1 || nj == n - 1)
                return dist[i][j];
            }
          }
        }
      }
    }
  }

  assert(false);
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  clr(danger, 1);
  int ans = 0;
  rep(k, 0, n * n) {
    int x;
    cin >> x;
    --x;
    int sti = x / n, stj = x % n;
    danger[sti][stj] = false;
    int temp = bfs(sti, stj);
    ans += temp;
  }

  cout << ans << '\\n';
}