Problem:


Score : 700 points

Problem Statement

Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2.

At the end of the movie, the viewers go out of the cinema in a certain order: the i-th viewer leaving her seat is the one denoted by the number P_i. The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat.
To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column).
While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.

Compute the number of pairs of viewers (x, y) such that y will hate x forever.

Constraints

2 \le N \le 500

The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \{1, 2, \dots, N^2\}.

Input

The input is given from Standard Input in the format

N
P_1 P_2 \cdots P_{N^2}

Output

If ans is the number of pairs of viewers described in the statement, you should print on Standard Output

ans

Sample Input 1

3
1 3 7 9 5 4 8 6 2

Sample Output 1

1

Before the end of the movie, the viewers are arranged in the cinema as follows:

1 2 3
4 5 6
7 8 9

The first four viewers leaving the cinema (1, 3, 7, 9) can leave the cinema without going through any seat, so they will not be hated by anybody.

Then, viewer 5 must go through one of the seats where viewers 2, 4, 6, 8 are currently seated while leaving the cinema; hence he will be hated by at least one of those viewers.

Finally the remaining viewers can leave the cinema (in the order 4, 8, 6, 2) without going through any occupied seat (actually, they can leave the cinema without going through any seat at all).

Sample Input 2

4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8

Sample Output 2

3

Sample Input 3

6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30

Sample Output 3

11



Sample input:
3
1 3 7 9 5 4 8 6 2


Sample output:
1

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3



n =  int(input())
numbers = input().split(" ")
r = 0

p = []
hate = [-1] * (n*n)
is_seated = [1] * (n*n)

def is_area(x, y):
  if x  >= 0 and x < n and y >= 0 and y < n:
    return True
  else:
    return False
    
def rewrite(x, y):
  global hate
  global is_seated
  global n
  
  index = (x) * n + (y)

  
  points = [[x, y-1], [x, y+1], [x+1, y], [x-1, y]]
  
  flag = 0
  for point in points:
    if is_area(point[0], point[1]):
      new_index = point[0] * n + point[1]
      if hate[new_index] == -1 or hate[new_index] > is_seated[index] + hate[index]:
        hate[new_index]  = is_seated[index] + hate[index]
        rewrite(point[0], point[1])
  return


for x in numbers:
  p.append(int(x))
  

for i in range(n):
  hate[i] = 0
  rewrite(0, 0)
  
  hate[n * n - n + i] = 0
  rewrite(n - 1, i)
  
  hate[i * n] = 0
  rewrite(i, 0)
  
  hate[i * n + n - 1] = 0
  rewrite(i, n - 1)
  
for k in p:
  for i in range(n):
    for j in range(n):
      rewrite(i, j)
      
  for ii in range(n):
    for jj in range(n):
      print(hate[ii * n + jj], end = "")
    print(" ", end = "")
    for jj in range(n):
      if k - 1 !=  ii * n + jj:
        print(is_seated[ii * n + jj], end = "")
      else:
         print("-", end = "")
    print()
  print()
  
  r += hate[k - 1]
  is_seated[k - 1] = 0
  
  
  
  
  
          
#for i in range(n):
#  for j in range(n):
#    print(hate[i * n + j], end = "")
#  print()

print(r)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import functools
import heapq
import itertools
import logging
import math
import os
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from io import BytesIO, IOBase
from typing import Dict, List, Optional, Set, Tuple

sys.setrecursionlimit(pow(2, 31) - 1)

UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3


def solve(values: List[int], nb: int) -> int:
    # nb of neighbours from here to exit from up, down, left, right
    grid = [[[i, nb - i - 1, j, nb - j - 1] for j in range(nb)] for i in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    answer = 0
    free_exit = set()
    for x in range(nb):
        free_exit.add((x, 0))
        free_exit.add((0, x))
    for v in values:
        i, j = divmod(v - 1, nb)
        result = dfs(nb, grid, i, j, free_exit, set())
        if not result:
            free_exit.add((i, j))
        answer += result
        update_neighbours(nb, grid, i, j, free_exit)
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def update_neighbours(
    nb: int, grid: List[List[int]], i: int, j: int, free_exit: Set[Tuple[int, int]]
):
    # update neighbours
    if j < nb - 1:
        grid[i][j][RIGHT] = grid[i][j + 1][RIGHT]
    if j > 0:
        grid[i][j][LEFT] = grid[i][j - 1][LEFT]
    if i < nb - 1:
        grid[i][j][UP] = grid[i + 1][j][UP]
    if i > 0:
        grid[i][j][DOWN] = grid[i - 1][j][DOWN]
    if 0 in grid[i][j]:
        free_exit.add((i, j))
    for left in range(j):
        grid[i][left][RIGHT] -= 1
        if grid[i][left][RIGHT] < 0:
            grid[i][left][RIGHT] = 0
            free_exit.add((i, left))
    for right in range(j + 1, nb):
        grid[i][right][LEFT] -= 1
        if grid[i][right][LEFT] < 0:
            grid[i][right][LEFT] = 0
            free_exit.add((i, right))
    for up in range(i):
        grid[up][j][DOWN] -= 1
        if grid[up][j][DOWN] < 0:
            grid[up][j][DOWN] = 0
            free_exit.add((up, i))
    for down in range(i + 1, nb):
        grid[down][j][UP] -= 1
        if grid[down][j][UP] < 0:
            grid[down][j][UP] = 0
            free_exit.add((down, i))


def dfs(
    nb: int,
    grid: List[List[int]],
    i: int,
    j: int,
    free_exit: Set[Tuple[int, int]],
    visited: Set[Tuple[int, int]],
) -> int:
    if i <= 0 or i >= nb - 1 or j <= 0 or j >= nb - 1:
        return 0
    if (i, j) in free_exit:
        return 0
    if 0 in grid[i][j]:
        return 0
    visited.add((i, j))
    return 1 + min(
        dfs(nb, grid, *neighbour, free_exit, visited)
        for neighbour in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
        if neighbour not in visited
    )


def do_job(stdin, stdout):
    "Do the work"
    LOG.debug("Start working")
    # first line is number of test cases
    N = int(stdin.readline().strip())
    values = list(map(int, stdin.readline().split()))
    # values = []
    # for _ in range(N):
    #     values.append(stdin.readline().split())
    result = solve(values, N)
    print(result, file=stdout)


def print_output(testcase: int, result, stdout) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result), file=stdout)
    # 6 digits float precision {:.6f} (6 is the default value)
    # print("Case #{}: {:f}".format(testcase + 1, result), file=stdout)


BUFSIZE = 8192


class FastIO(IOBase):
    # pylint: disable=super-init-not-called, expression-not-assigned
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    # pylint: disable=super-init-not-called
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def configure_log() -> None:
    "Configure the log output"
    log_formatter = logging.Formatter("L%(lineno)d - " "%(message)s")
    handler = logging.StreamHandler(IOWrapper(sys.stderr))
    handler.setFormatter(log_formatter)
    LOG.addHandler(handler)


LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
    LOG = logging.getLogger("template")
    configure_log()


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="run as verbose mode",
    )
    args = parser.parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)
    stdin = IOWrapper(sys.stdin)
    stdout = IOWrapper(sys.stdout)
    do_job(stdin, stdout)
    stdout.flush()
    for h in LOG.handlers:
        h.flush()
    return 0


if __name__ == "__main__":
    sys.exit(main())

Submission status: Runtime Error

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit('(i4,i4[::1])', cache=True)
def solve(N, P):
    W = N + 2
    dp = np.zeros((W, W), np.int32)
    for _ in range(4):
        dp = dp.T[::-1]
        for n in range(1, (N + 1) // 2 + 1):
            dp[n, n:-n] = n
    filled = np.zeros_like(dp)
    filled[1:-1, 1:-1] = 1
    dp = dp.ravel()
    filled = filled.ravel()
    stack = np.empty_like(dp)
    ans = 0
    for n in P:
        n -= 1
        h, w = divmod(n, N)
        v = (h + 1) * W + (w + 1)
        ans += dp[v] - 1
        filled[v] = 0
        k = min(dp[v - 1], dp[v + 1], dp[v - W], dp[v + W])
        if dp[v] == k:
            return ans
        p = 0
        stack[0] = v
        dp[v] = k
        while p >= 0:
            v = stack[p]
            p -= 1
            for dx in (-1, 1, -W, W):
                w = v + dx
                k = dp[v] + filled[w]
                if dp[w] > k:
                    dp[w] = k
                    p += 1
                    stack[p] = w
    return ans

N = int(readline())
P = np.array(read().split(), np.int32)

print(solve(N, P))

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def solve(N, P):
    W = N + 2
    dp = np.zeros((W, W), np.int32)
    for _ in range(4):
        dp = dp.T[::-1]
        for n in range(1, (N + 1) // 2 + 1):
            dp[n, n:-n] = n
    filled = np.zeros_like(dp)
    filled[1:-1, 1:-1] = 1
    dp = dp.ravel()
    filled = filled.ravel()
    stack = np.empty_like(dp)
    ans = 0
    for n in P:
        n -= 1
        h, w = divmod(n, N)
        v = (h + 1) * W + (w + 1)
        ans += dp[v] - 1
        filled[v] = 0
        k = min(dp[v - 1], dp[v + 1], dp[v - W], dp[v + W])
        if dp[v] == k:
            return ans
        p = 0
        stack[0] = v
        dp[v] = k
        while p >= 0:
            v = stack[p]
            p -= 1
            for dx in (-1, 1, -W, W):
                w = v + dx
                k = dp[v] + filled[w]
                if dp[w] > k:
                    dp[w] = k
                    p += 1
                    stack[p] = w
    return ans

N = int(readline())
P = np.array(list(map(int, read().split())), np.int32)

print(solve(N, P))

Submission status: Runtime Error

Solution code:
import numpy as np
import collections

N = int(input())
Plist = list(map(int , input().split()))

point_array = np.empty((N+2,N+2), dtype = int)

for i in range(N+2):
    for j in range(N+2):
        point_array[i][j] = min(i-1, j-1, N+2-i-2, N+2-j-2)
        if(point_array[i][j] == -1):
            point_array[i][j] = 0

#print(point_array)

calcDeque = collections.deque()
for P in Plist:
    calcDeque.append(P)

ans = 0
while len(calcDeque) != 0:
    toridashi = calcDeque.popleft()

    i = (toridashi) // N + 1
    j = (toridashi) % N

    if(j == 0):
        i -= 1
        j = 4
#    print(toridashi)
#    print(i,j)
    ans += point_array[i][j]
    if(point_array[i][j-1] > point_array[i][j]):
        point_array[i][j-1] = min(point_array[i][j+1], point_array[i+1][j], point_array[i-1][j]) +1
        calcDeque.appendleft(i * N + j - 1)

    if(point_array[i-1][j] > point_array[i][j]):
        point_array[i-1][j] = min(point_array[i][j+1], point_array[i+1][j], point_array[i][j-1]) +1
        calcDeque.appendleft((i-1) * N + j)

    if(point_array[i+1][j] > point_array[i][j]):
        point_array[i+1][j] = min(point_array[i][j+1], point_array[i][j-1], point_array[i-1][j]) +1
        calcDeque.appendleft((i+1) * N + j)

    if(point_array[i][j+1] > point_array[i][j]):
        point_array[i][j+1] = min(point_array[i][j-1], point_array[i+1][j], point_array[i-1][j]) +1
        calcDeque.appendleft(i * N + j + 1)

    point_array[i][j] = 0
#    print(point_array)
#    print(ans)

print(ans)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def solve(N, P):
    W = N + 2
    dp = np.zeros((W, W), np.int32)
    for _ in range(4):
        dp = dp.T[::-1]
        for n in range(1, (N + 1) // 2 + 1):
            dp[n, n:-n] = n
    filled = np.zeros_like(dp)
    filled[1:-1, 1:-1] = 1
    dp = dp.ravel()
    filled = filled.ravel()
    stack = np.empty_like(dp)
    ans = 0
    for n in P:
        n -= 1
        h, w = divmod(n, N)
        v = (h + 1) * W + (w + 1)
        ans += dp[v] - 1
        filled[v] = 0
        k = min(dp[v - 1], dp[v + 1], dp[v - W], dp[v + W])
        if dp[v] == k:
            return ans
        p = 0
        stack[0] = v
        dp[v] = k
        while p >= 0:
            v = stack[p]
            p -= 1
            for dx in (-1, 1, -W, W):
                w = v + dx
                k = dp[v] + filled[w]
                if dp[w] > k:
                    dp[w] = k
                    p += 1
                    stack[p] = w
    return ans

N = int(readline())
P = np.array(read().split(), np.int32)

print(solve(N, P))

Submission status: Runtime Error

Solution code:
import numba
import numpy as np
N = int(input())
P = [int(c)-1 for c in input().split()]
@numba.njit("void(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((N, N), dtype=np.int32)
    Mat = np.zeros((N, N), dtype=np.int32)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    #print(Mat)
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y][x]
        #print(p, Mat[y][x])
        Removed[y][x] = True
        #Mat[y][x] -= 1
        st = [(y, x)]
        while st:
            vy, vx = st.pop()
            vr = Removed[vy][vx]
            val = Mat[vy][vx]
            for dy, dx in zip(Dy, Dx):
                uy = vy + dy
                ux = vx + dx
                if not (0<=uy<N and 0<=ux<N):
                    continue
                ur = Removed[uy][ux]
                if vr:
                    if Mat[uy][ux] >= val+1:
                        Mat[uy][ux] = val
                        st.append((uy, ux))
                else:
                    if Mat[uy][ux] >= val+2:
                        Mat[uy][ux] = val+1
                        st.append((uy, ux))
    # for m in Mat:
    #     print(m)
    print(ans)
proc(N, P)

Submission status: Runtime Error

Solution code:
from random import shuffle
import numba
import numpy as np
N = int(input())
#P = list(range(N*N))
#shuffle(P)
P = int(c)-1 for c in input().split()]
#shuffle(P)
#N = int(input())
#P = [int(c)-1 for c in input().split()]
# Mat = [[min(y, N-1-y, x, N-1-x) for y in range(N)] for x in range(N)]
# Mat = np.array(Mat)
@numba.njit()
def proc(N, P):
    ans = 0
    Removed = np.zeros((N, N), dtype=np.int32)
    Mat = np.zeros((N, N), dtype=np.int32)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    #print(Mat)
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y][x]
        #print(p, Mat[y][x])
        Removed[y][x] = True
        #Mat[y][x] -= 1
        st = [(y, x)]
        while st:
            vy, vx = st.pop()
            vr = Removed[vy][vx]
            val = Mat[vy][vx]
            for dy, dx in zip(Dy, Dx):
                uy = vy + dy
                ux = vx + dx
                if not (0<=uy<N and 0<=ux<N):
                    continue
                ur = Removed[uy][ux]
                if vr:
                    if Mat[uy][ux] >= val+1:
                        Mat[uy][ux] = val
                        st.append((uy, ux))
                else:
                    if Mat[uy][ux] >= val+2:
                        Mat[uy][ux] = val+1
                        st.append((uy, ux))
    # for m in Mat:
    #     print(m)
    print(ans)
proc(N, P)

Submission status: Runtime Error

Solution code:
import os

import itertools
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


# MOD = 998244353


def test():
    ans_hist = [INF] * (N ** 2)

    ans = 0
    dist = [INF] * (N ** 2)
    for i, p in enumerate(P):
        p -= 1
        ph, pw = p // N, p % N
        d = min(ph, pw, N - ph - 1, N - pw - 1)

        j = i - 1
        while j >= 0:
            q = P[j] - 1
            qh, qw = q // N, q % N
            d = min(d, dist[q] + abs(ph - qh) + abs(pw - qw) - 1)
            j -= 1

        dist[p] = d
        ans_hist[p] = d

        j = i - 1
        while j >= 0:
            q = P[j] - 1
            qh, qw = q // N, q % N
            dist[q] = min(dist[q], dist[p] + abs(ph - qh) + abs(pw - qw) - 1)
            j -= 1

        ans += d
        # print(p, dist)
    print(ans)
    # print(dist)
    # print(np.array(ans_hist, dtype=int).reshape(N, N))
    return ans


N = int(sys.stdin.buffer.readline())
P = list(map(int, sys.stdin.buffer.readline().split()))

# 解説
dist = [[INF] * N for _ in range(N)]
for h, w in itertools.product(range(N), range(N)):
    dist[h][w] = min(h, w, N - h - 1, N - w - 1)
present = [True] * (N ** N)

ans = 0
for p in P:
    p -= 1
    h, w = p // N, p % N
    present[p] = False

    ans += dist[h][w]
    stack = [(h, w, dist[h][w])]
    while stack:
        h, w, d = stack.pop()
        d += present[h * N + w]
        for dh, dw in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            if 0 <= h + dh < N and 0 <= w + dw < N:
                if d < dist[h + dh][w + dw]:
                    dist[h + dh][w + dw] = d
                    stack.append((h + dh, w + dw, d))
print(ans)
# test()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3



n =  int(input())
numbers = input().split(" ")
r = 0

p = []
hate = [-1] * (n*n)
is_seated = [1] * (n*n)

def is_area(x, y):
  if x  >= 0 and x < n and y >= 0 and y < n:
    return True
  else:
    return False
    
def rewrite(x, y):
  global hate
  global is_seated
  global n
  
  index = (x) * n + (y)

  
  points = [[x, y-1], [x, y+1], [x+1, y], [x+1, y]]
  
  flag = 0
  for point in points:
    if is_area(point[0], point[1]):
      new_index = point[0] * n + point[1]
      if hate[new_index] == -1 or hate[new_index] > is_seated[index] + hate[index]:
        hate[new_index]  = is_seated[index] + hate[index]
        rewrite(point[0], point[1])
  return


for x in numbers:
  p.append(int(x))
  

for i in range(n):
  hate[i] = 0
  hate[n * n - n + i] = 0
  hate[i * n] = 0
  hate[i * n + n - 1] = 0
  
for k in p:
  for i in range(n):
    for j in range(n):
      rewrite(i, j)
  r += hate[k - 1]
  is_seated[k - 1] = 0
  
  
#  for ii in range(n):
#    for jj in range(n):
#      print(hate[ii * n + jj], end = "")
#    print()
#  print()
  
  
          
#for i in range(n):
#  for j in range(n):
#    print(hate[i * n + j], end = "")
#  print()

print(r)

Submission status: Runtime Error

Solution code:
from random import shuffle
N = int(input())
P = [int(c)-1 for c in input().split()]
#shuffle(P)
import numba
import numpy as np
#N = int(input())
#P = [int(c)-1 for c in input().split()]
# Mat = [[min(y, N-1-y, x, N-1-x) for y in range(N)] for x in range(N)]
# Mat = np.array(Mat)
#@numba.njit()
def proc(N, P):
    ans = 0
    Removed = np.zeros((N, N), dtype=np.int32)
    closed = np.zeros((N,N), dtype=np.int32)
    Mat = np.zeros((N, N), dtype=np.int32)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    for i in range(N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y][x]
        #print(p, Mat[y][x])
        Removed[y][x] = True
        #Mat[y][x] -= 1
        st = [(y, x)]
        clsd = [(y, x)]
        closed[y][x] = True
        while st:
            vy, vx = st.pop()
            vr = Removed[vy][vx]
            val = Mat[vy][vx]
            for dy, dx in zip(Dy, Dx):
                uy = vy + dy
                ux = vx + dx
                if not (0<=uy<N and 0<=ux<N):
                    continue
                ur = Removed[uy][ux]
                if vr:
                    if Mat[uy][ux] >= val+1:
                        Mat[uy][ux] = val
                        st.append((uy, ux))
                else:
                    if Mat[uy][ux] >= val+2:
                        Mat[uy][ux] = val+1
                        st.append((uy, ux))
        for y, x in clsd:
            closed[y][x] = False
    # for m in Mat:
    #     print(m)
    print(ans)
proc(N, P)

Submission status: Runtime Error

Solution code:
def hantei(j,x):
  ll=gl[j]
  for k in ll:
    if ti[k]>x:
      ti[k]=x
      if ls[k]==-1:
        hantei(k,x)
n=int(input())
ans=0
que=list(map(int,input().split()))
n=500
que=list(range(250000))
random.shuffle(que
gl={}
ti={}
ls=[0]*(n**2)
for i in range(n):
  for j in range(n):
    l=[]
    if i!=0:
      l.append(n*(i-1)+j)
    if i!=n-1:
      l.append(n*(i+1)+j)
    if j!=0:
      l.append(n*i+j-1)
    if j!=n-1:
      l.append(n*i+j+1)
    jj=min(j,n-1-j)
    ii=min(i,n-1-i)
    gl[n*i+j]=l
    ti[n*i+j]=min(ii,jj)
for i in que:
  j=i-1
  x=ti[j]
  
  hantei(j,x)
  ans+=x
  ls[j]=-1
print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import functools
import heapq
import itertools
import logging
import math
import os
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from io import BytesIO, IOBase
from typing import Dict, List, Optional, Set, Tuple

sys.setrecursionlimit(pow(2, 31) - 1)

UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3


def solve(values: List[int], nb: int) -> int:
    # nb of neighbours from here to exit from up, down, left, right
    grid = [[[i, nb - i - 1, j, nb - j - 1] for j in range(nb)] for i in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    answer = 0
    free_exit = set()
    for x in range(nb):
        free_exit.add((x, 0))
        free_exit.add((0, x))
    for v in values:
        i, j = divmod(v - 1, nb)
        result = dfs(nb, grid, i, j, free_exit, set())
        # result = min(grid[i][j])
        # LOG.debug((i, j, result))
        answer += result
        update_neighbours(nb, grid, i, j, free_exit)
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def update_neighbours(
    nb: int, grid: List[List[int]], i: int, j: int, free_exit: Set[Tuple[int, int]]
):
    # update neighbours
    if j < nb - 1:
        grid[i][j][RIGHT] = grid[i][j + 1][RIGHT]
    if j > 0:
        grid[i][j][LEFT] = grid[i][j - 1][LEFT]
    if i < nb - 1:
        grid[i][j][UP] = grid[i + 1][j][UP]
    if i > 0:
        grid[i][j][DOWN] = grid[i - 1][j][DOWN]
    for left in range(j):
        grid[i][left][RIGHT] -= 1
        if grid[i][left][RIGHT] < 0:
            grid[i][left][RIGHT] = 0
            free_exit.add((i, left))
    for right in range(j + 1, nb):
        grid[i][right][LEFT] -= 1
        if grid[i][right][LEFT] < 0:
            grid[i][right][LEFT] = 0
            free_exit.add((i, right))
    for up in range(i):
        grid[up][j][DOWN] -= 1
        if grid[up][j][DOWN] < 0:
            grid[up][j][DOWN] = 0
            free_exit.add((up, i))
    for down in range(i + 1, nb):
        grid[down][j][UP] -= 1
        if grid[down][j][UP] < 0:
            grid[down][j][UP] = 0
            free_exit.add((down, i))


def dfs(
    nb: int,
    grid: List[List[int]],
    i: int,
    j: int,
    free_exit: Set[Tuple[int, int]],
    visited: Set[Tuple[int, int]],
) -> int:
    if i <= 0 or i >= nb - 1 or j <= 0 or j >= nb - 1:
        return 0
    if (i, j) in free_exit:
        return 0
    if 0 in grid[i][j]:
        return 0
    visited.add((i, j))
    return 1 + min(
        dfs(nb, grid, *neighbour, free_exit, visited)
        for neighbour in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
        if neighbour not in visited
    )


def do_job(stdin, stdout):
    "Do the work"
    LOG.debug("Start working")
    # first line is number of test cases
    N = int(stdin.readline().strip())
    values = list(map(int, stdin.readline().split()))
    # values = []
    # for _ in range(N):
    #     values.append(stdin.readline().split())
    result = solve(values, N)
    print(result, file=stdout)


def print_output(testcase: int, result, stdout) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result), file=stdout)
    # 6 digits float precision {:.6f} (6 is the default value)
    # print("Case #{}: {:f}".format(testcase + 1, result), file=stdout)


BUFSIZE = 8192


class FastIO(IOBase):
    # pylint: disable=super-init-not-called, expression-not-assigned
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    # pylint: disable=super-init-not-called
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def configure_log() -> None:
    "Configure the log output"
    log_formatter = logging.Formatter("L%(lineno)d - " "%(message)s")
    handler = logging.StreamHandler(IOWrapper(sys.stderr))
    handler.setFormatter(log_formatter)
    LOG.addHandler(handler)


LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
    LOG = logging.getLogger("template")
    configure_log()


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="run as verbose mode",
    )
    args = parser.parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)
    stdin = IOWrapper(sys.stdin)
    stdout = IOWrapper(sys.stdout)
    do_job(stdin, stdout)
    stdout.flush()
    for h in LOG.handlers:
        h.flush()
    return 0


if __name__ == "__main__":
    sys.exit(main())