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: Time Limit Exceeded

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:
    # min nb of neighbours from here to exit
    grid = [[min(i, nb - i - 1, j, nb - j - 1) for j in range(nb)] for i in range(nb)]
    answer = 0
    still_inside = [[True] * nb for _ in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    for v in values:
        i, j = divmod(v - 1, nb)
        answer += grid[i][j]
        # LOG.debug((i, j, grid[i][j]))
        still_inside[i][j] = False
        new_score = min(
            still_inside[next_i][next_j] + grid[next_i][next_j]
            for next_i, next_j in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
            if 0 <= next_i < nb and 0 <= next_j < nb
        )
        if new_score < grid[i][j]:
            grid[i][j] = new_score
        dfs(nb, grid, i, j, still_inside)
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def dfs(
    nb: int,
    grid: List[List[int]],
    removed_i: int,
    removed_j: int,
    still_inside: List[List[bool]],
):
    q = deque([(removed_i, removed_j, grid[removed_i][removed_j])])
    while q:
        i, j, cur_cost = q.pop()
        for next_i, next_j in (
            (i + 1, j),
            (i - 1, j),
            (i, j + 1),
            (i, j - 1),
        ):
            if (
                0 <= next_i < nb
                and 0 <= next_j < nb
                and grid[next_i][next_j] > cur_cost + still_inside[i][j]
            ):
                grid[next_i][next_j] = cur_cost + still_inside[i][j]
                q.append((next_i, next_j, grid[next_i][next_j]))


def update_neighbours(nb: int, grid: List[List[int]], i: int, j: 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] = max(0, grid[i][left][RIGHT])
    for right in range(j + 1, nb):
        grid[i][right][LEFT] = max(0, grid[i][right][LEFT])
    for up in range(i):
        grid[up][j][DOWN] = max(0, grid[up][j][DOWN])
    for down in range(i + 1, nb):
        grid[down][j][UP] = max(0, grid[down][j][UP])


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: Time Limit Exceeded

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:
    # min nb of neighbours from here to exit
    grid = [[min(i, nb - i - 1, j, nb - j - 1) for j in range(nb)] for i in range(nb)]
    answer = 0
    still_inside = [[True] * nb for _ in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    for v in values:
        i, j = divmod(v - 1, nb)
        answer += grid[i][j]
        # LOG.debug((i, j, grid[i][j]))
        still_inside[i][j] = False
        new_score = min(
            still_inside[next_i][next_j] + grid[next_i][next_j]
            for next_i, next_j in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
            if 0 <= next_i < nb and 0 <= next_j < nb
        )
        if new_score < grid[i][j]:
            grid[i][j] = new_score
        dfs(nb, grid, i, j, still_inside)
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def dfs(
    nb: int,
    grid: List[List[int]],
    removed_i: int,
    removed_j: int,
    still_inside: List[List[bool]],
):
    q = deque([(removed_i, removed_j)])
    while q:
        i, j = q.pop()
        for next_i, next_j in (
            (i + 1, j),
            (i - 1, j),
            (i, j + 1),
            (i, j - 1),
        ):
            if (
                0 <= next_i < nb
                and 0 <= next_j < nb
                and grid[next_i][next_j] > grid[i][j] + still_inside[i][j]
            ):
                grid[next_i][next_j] = grid[i][j] + still_inside[i][j]
                if still_inside[i][j]:
                    q.append((next_i, next_j))
                else:
                    q.appendleft((next_i, next_j))


def update_neighbours(nb: int, grid: List[List[int]], i: int, j: 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] = max(0, grid[i][left][RIGHT])
    for right in range(j + 1, nb):
        grid[i][right][LEFT] = max(0, grid[i][right][LEFT])
    for up in range(i):
        grid[up][j][DOWN] = max(0, grid[up][j][DOWN])
    for down in range(i + 1, nb):
        grid[down][j][UP] = max(0, grid[down][j][UP])


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: Time Limit Exceeded

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:
    # min nb of neighbours from here to exit
    grid = [[min(i, nb - i - 1, j, nb - j - 1) for j in range(nb)] for i in range(nb)]
    answer = 0
    still_inside = [[True] * nb for _ in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    for v in values:
        i, j = divmod(v - 1, nb)
        answer += grid[i][j]
        # LOG.debug((i, j, grid[i][j]))
        still_inside[i][j] = 0
        new_score = min(
            still_inside[next_i][next_j] + grid[next_i][next_j]
            for next_i, next_j in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
            if 0 <= next_i < nb and 0 <= next_j < nb
        )
        if new_score < grid[i][j]:
            grid[i][j] = new_score
        dfs(nb, grid, i, j, still_inside)
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def dfs(
    nb: int,
    grid: List[List[int]],
    removed_i: int,
    removed_j: int,
    still_inside: List[List[bool]],
):
    q = [(removed_i, removed_j)]
    while q:
        i, j = q.pop()
        for next_i, next_j in (
            (i + 1, j),
            (i - 1, j),
            (i, j + 1),
            (i, j - 1),
        ):
            if next_i < 0 or next_i >= nb or next_j < 0 or next_j >= nb:
                continue
            if grid[next_i][next_j] > grid[i][j] + still_inside[i][j]:
                grid[next_i][next_j] = grid[i][j] + still_inside[i][j]
                q.append((next_i, next_j))


def update_neighbours(nb: int, grid: List[List[int]], i: int, j: 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] = max(0, grid[i][left][RIGHT])
    for right in range(j + 1, nb):
        grid[i][right][LEFT] = max(0, grid[i][right][LEFT])
    for up in range(i):
        grid[up][j][DOWN] = max(0, grid[up][j][DOWN])
    for down in range(i + 1, nb):
        grid[down][j][UP] = max(0, grid[down][j][UP])


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: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    seats = [-1] * (n2 * n2)
    is_seated = [False] * (n2 * n2)
    for i in range(n):
        ud = min(i, n - 1 - i)
        for j in range(n):
            ij = (i + 1) * n2 + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = True

    ans = 0

    for p in ppp:
        i, j = divmod(p - 1, n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = False

        q = [(res, i)]
        while q:
            val, j = heappop(q)
            seats[j] = val
            if is_seated[j]:
                val += 1

            nj = j - n2
            if seats[nj] > val:
                heappush(q, (val, nj))
            nj = j - 1
            if seats[nj] > val:
                heappush(q, (val, nj))
            nj = j + 1
            if seats[nj] > val:
                heappush(q, (val, nj))
            nj = j + n2
            if seats[nj] > val:
                heappush(q, (val, nj))

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7

def bfs(src):
    from collections import deque

    directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
    que = deque()
    h, w = src
    que.append((0, h, w))
    visited = list2d(N, N, 0)
    visited[h][w] = 1
    while que:
        cost, h, w = que.popleft()
        for dh, dw in directions:
            h2 = h + dh
            w2 = w + dw
            if h2 < 0 or w2 < 0 or h2 >= N or w2 >= N:
                h, w = src
                dist[h][w] = cost
                return cost
            if visited[h2][w2]:
                continue
            visited[h2][w2] = 1
            if dist[h2][w2] == -1:
                que.appendleft((cost, h2, w2))
            else:
                que.append((cost+1, h2, w2))

N = INT()
P = [p-1 for p in LIST()]

grid = list2d(N, N, -1)
for i in range(N):
    for j in range(N):
        grid[i][j] = i*N + j

dist = list2d(N, N, -1)
ans = 0
for p in P[::-1]:
    h, w = p//N, p%N
    ans += bfs((h, w))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
S=list(map(int,input().split()))
count=0
P=[0]*(N*N+1)
for j in range(N*N):
  P[j+1]=S.index(j+1)
d=[-1]*(N*N+1)
for i in range(N*N):
  player=S[i]
  hayasa=P[player]
  
  que=[[] for _ in range(N)]
  que[0].append(player)
  d[player]=i
  
  j=0
  finish=0
  while True:
    for kouho in que[j]:
      if kouho%N==0:
        finish=1
        break
      if kouho%N==1:
        finish=1
        break
      if kouho+N>N*N:
        finish=1
        break
      if kouho<N:
        finish=1
        break
        
      if d[kouho+N]<i:
        if P[kouho+N]>hayasa:
          que[j+1].append(kouho+N)
          d[kouho+N]=i
        else:
          que[j].append(kouho+N)
          d[kouho+N]=i
          
      if d[kouho-N]<i:
        if P[kouho-N]>hayasa:
          que[j+1].append(kouho-N)
          d[kouho-N]=i
        else:
          que[j].append(kouho-N)
          d[kouho-N]=i
          
      if d[kouho+1]<i:
        if P[kouho+1]>hayasa:
          que[j+1].append(kouho+1)
          d[kouho+1]=i
        else:
          que[j].append(kouho+1)
          d[kouho+1]=i
          
      if d[kouho-1]<i:
        if P[kouho-1]>hayasa:
          que[j+1].append(kouho-1)
          d[kouho-1]=i
        else:
          que[j].append(kouho-1)
          d[kouho-1]=i
    if finish==1:
      count+=j
      break
    j+=1    
print(count)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
S=list(map(int,input().split()))
count=0
P=[0]*(N*N+1)
for j in range(N*N):
  P[j+1]=S.index(j+1)
for i in range(N*N):
  player=S[i]
  hayasa=P[player]
  
  que=[[] for _ in range(N)]
  d=[-1]*(N*N+1)
  que[0].append(player)
  d[player]=i
  
  j=0
  finish=0
  while True:
    for kouho in que[j]:
      if kouho%N==0:
        finish=1
        break
      if kouho%N==1:
        finish=1
        break
      if kouho+N>N*N:
        finish=1
        break
      if kouho<N:
        finish=1
        break
        
      if d[kouho+N]<i:
        if P[kouho+N]>hayasa:
          que[j+1].append(kouho+N)
          d[kouho+N]=i
        else:
          que[j].append(kouho+N)
          d[kouho+N]=i
          
      if d[kouho-N]<i:
        if P[kouho-N]>hayasa:
          que[j+1].append(kouho-N)
          d[kouho-N]=i
        else:
          que[j].append(kouho-N)
          d[kouho-N]=i
          
      if d[kouho+1]<i:
        if P[kouho+1]>hayasa:
          que[j+1].append(kouho+1)
          d[kouho+1]=i
        else:
          que[j].append(kouho+1)
          d[kouho+1]=i
          
      if d[kouho-1]<i:
        if P[kouho-1]>hayasa:
          que[j+1].append(kouho-1)
          d[kouho-1]=i
        else:
          que[j].append(kouho-1)
          d[kouho-1]=i
    if finish==1:
      count+=j
      break
    j+=1    
print(count)

Submission status: Time Limit Exceeded

Solution code:
def main():
    n = int(input())
    a = list(map(int, input().split()))
    a = [((i-1)//n, (i-1) % n) for i in a]
    b = [[min(i, n-i-1, j, n-j-1) for j in range(n)] for i in range(n)]
    sit = [[True for j in range(n)] for i in range(n)]
    ans = 0
    for i, j in a:
        sit[i][j] = False
        ans += b[i][j]
        q = [(i, j, b[i][j])]
        while q:
            x, y, z = q.pop()
            if x != 0:
                if b[x-1][y] > z:
                    b[x-1][y] = z
                    q.append((x-1, y, z+sit[x-1][y]))
            if x != n-1:
                if b[x+1][y] > z:
                    b[x+1][y] = z
                    q.append((x+1, y, z+sit[x+1][y]))
            if y != 0:
                if b[x][y-1] > z:
                    b[x][y-1] = z
                    q.append((x, y-1, z+sit[x][y-1]))
            if y != n-1:
                if b[x][y+1] > z:
                    b[x][y+1] = z
                    q.append((x, y+1, z+sit[x][y+1]))
    print(ans)


main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush
import numpy as np

from numba import njit


# def pg(aaa):
#     for i in range(0, n2 ** 2, n2):
#         print(aaa[i:i + n2])
#     print()


@njit
def bfs(n2, s, seats, is_seated):
    q = [s]

    while q:
        val, j = heappop(q)
        seats[j] = val
        if is_seated[j]:
            val += 1

        nj = j - n2
        if seats[nj] > val:
            heappush(q, (val, nj))
        nj = j - 1
        if seats[nj] > val:
            heappush(q, (val, nj))
        nj = j + 1
        if seats[nj] > val:
            heappush(q, (val, nj))
        nj = j + n2
        if seats[nj] > val:
            heappush(q, (val, nj))


@njit
def solve(n, ppp):
    n2 = n + 2
    seats = [-1] * (n2 * n2)
    is_seated = [False] * (n2 * n2)
    for i in range(n):
        ud = min(i, n - 1 - i)
        for j in range(n):
            ij = (i + 1) * n2 + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = True

    ans = 0

    for p in ppp:
        i, j = divmod(p - 1, n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = False
        bfs(n2, (res, i), seats, is_seated)

    print(ans)


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
solve(n, ppp)

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
from numba import jit
import sys
from collections import deque
#input = sys.stdin.readline
n = int(input())
p = [int(i)-1 for i in input().split()]
c = [[1]*n for _ in range(n)] 
d = [[0]*n for _ in range(n)] 

@jit
def main():
    for x in range(n):
        for y in range(n):
            d[y][x] = min(x, n-x-1, y, n-y-1)
    ans = 0
    
    for i in p:
        x, y = i%n, i//n
        c[y][x] = 0
        ans += d[y][x]
        que = deque([[x, y]])
        while que:
            x, y = que.pop()
            for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
                nx, ny = x+dx, y+dy
                if 1<=nx<n-1 and 1<=ny<n-1:
                    if d[y][x]+c[y][x]<d[ny][nx]:
                        d[ny][nx] = d[y][x]+c[y][x]
                        que.append([nx, ny])
    
    return print(ans)
    
main()