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

Solution (Python):






"""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



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


def solve(values: List[int], nb: int) -> int:
    
    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)]
    
    for v in values:
        i, j = divmod(v - 1, nb)
        answer += grid[i][j]
        
        still_inside[i][j] = False
        dfs(nb, grid, i, j, still_inside)
        
    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()
        if i > 0 and grid[i - 1][j] > cur_cost:
            grid[i - 1][j] = cur_cost
            q.append((i - 1, j, cur_cost + still_inside[i - 1][j]))
        if j > 0 and grid[i][j - 1] > cur_cost:
            grid[i][j - 1] = cur_cost
            q.append((i, j - 1, cur_cost + still_inside[i][j - 1]))
        if i < nb - 1 and grid[i + 1][j] > cur_cost:
            grid[i + 1][j] = cur_cost
            q.append((i + 1, j, cur_cost + still_inside[i + 1][j]))
        if j < nb - 1 and grid[i][j + 1] > cur_cost:
            grid[i][j + 1] = cur_cost
            q.append((i, j + 1, cur_cost + still_inside[i][j + 1]))


def update_neighbours(nb: int, grid: List[List[int]], i: int, j: int):
    
    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")
    
    N = int(stdin.readline().strip())
    values = list(map(int, 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 
    
    


BUFSIZE = 8192


class FastIO(IOBase):
    
    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):
    
    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

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())

Solution (Python):
n = int(input())
P = list(map(int, input().split()))

dist = [[min(i, j, n - i - 1, n - j - 1) for j in range(n)] for i in range(n)]
is_sit = [[True for _ in range(n)] for _ in range(n)]

ans = 0
for p in P:
    i, j = divmod(p - 1, n)
    is_sit[i][j] = False
    ans += dist[i][j]

    q = [(i, j, dist[i][j])]
    while q:
        i, j, cur_cost = q.pop()

        if i > 0 and dist[i - 1][j] > cur_cost:
            dist[i - 1][j] = cur_cost
            q.append((i - 1, j, cur_cost + is_sit[i - 1][j]))

        if j > 0 and dist[i][j - 1] > cur_cost:
            dist[i][j - 1] = cur_cost
            q.append((i, j - 1, cur_cost + is_sit[i][j - 1]))

        if i < n - 1 and dist[i + 1][j] > cur_cost:
            dist[i + 1][j] = cur_cost
            q.append((i + 1, j, cur_cost + is_sit[i + 1][j]))

        if j < n - 1 and dist[i][j + 1] > cur_cost:
            dist[i][j + 1] = cur_cost
            q.append((i, j + 1, cur_cost + is_sit[i][j + 1]))

print(ans)

Solution (Python):
import sys
import numpy as np
from numba import njit
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


@njit("i4(i4,i4[:])", cache=True)
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    Dy, Dx = np.array([1,0,-1,0]), np.array([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)
    
    Buf = [(0, 0) for _ in range(1<<17)]
    Buf_idx = 0
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        Buf[Buf_idx] = (y, x)
        Buf_idx += 1
        while Buf_idx:
            Buf_idx -= 1
            vy, vx = Buf[Buf_idx]
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            
            for j in range(4):
                uy, ux = vy + Dy[j], vx + Dx[j]
                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
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
                else:
                    if Mat[uy,ux] >= val+2:
                        Mat[uy,ux] = val+1
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
    return ans

N = int(readline())
P = np.array(read().split(), np.int32)-1
 
print(proc(N, P))

Solution (Python):
cin = open(0).read().strip().split('\n')
n = int(cin[0])
p = list(map(int, cin[1].split(' ')))

space = [1]*(n*n)

dist = [0]*(n*n)
for r in range(n):
    for c in range(n):
        dist[r*n+c] = min(r, (n-1)-r, c, (n-1)-c)

ans = 0
for pi in p:
    pi -= 1
    q = [pi]
    ans += dist[pi]
    space[pi] = 0

    while q:
        pp = q.pop()
        for dxi in [-n,-1,1,n]:
            if dxi == 1 and pp % n==n-1: continue
            if dxi == -1 and pp % n ==n: continue
            if 0<=pp+dxi<n*n and dist[pp+dxi] > dist[pp]+space[pp]:
                q.append(pp+dxi)
                dist[pp+dxi] = dist[pp]+space[pp]

print(ans)

Solution (Python):



import sys
readline = sys.stdin.readline
read = sys.stdin.read

n,*p = map(int,read().split())
N = n*n

dist = [0]*N

for a in range(n):
    for b in range(n):
        dist[a*n+b] = min(a,n-1-a,b,n-1-b)





ans = 0
iru = [1]*N

for pi in p:
    pi -= 1

    ans += dist[pi]
    iru[pi] = 0

    q = [pi]
    
    
    while q:
        
        v = q.pop()
        for i in [-n,-1,1,n]:
            if i==1 and v%n==n-1: continue
            if i==-1 and v%n==0: continue
            nv = v+i
            if 0 <= nv < N and dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        
                    
    

print(ans)

Solution (Python):
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])







@numba.njit("i8(i8,i8[:])", cache=True)
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    Dy, Dx = np.array([1,0,-1,0]), np.array([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)
    
    Buf = [(0, 0) for _ in range(1<<17)]
    Buf_idx = 0
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        Buf[Buf_idx] = (y, x)
        Buf_idx += 1
        while Buf_idx:
            Buf_idx -= 1
            vy, vx = Buf[Buf_idx]
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            
            for j in range(4):
                uy, ux = vy + Dy[j], vx + Dx[j]
                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
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
                else:
                    if Mat[uy,ux] >= val+2:
                        Mat[uy,ux] = val+1
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
    
    
    return ans
print(proc(N, P))

Solution (Python):
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])







@numba.njit("i8(i8,i8[:])", cache=True)
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    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)
    
    Buf = [(0, 0) for _ in range(1<<17)]
    Buf_idx = 0
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        Buf[Buf_idx] = (y, x)
        Buf_idx += 1
        while Buf_idx:
            Buf_idx -= 1
            vy, vx = Buf[Buf_idx]
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            
            for j in range(4):
                uy, ux = vy + Dy[j], vx + Dx[j]
                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
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
                else:
                    if Mat[uy,ux] >= val+2:
                        Mat[uy,ux] = val+1
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
    
    
    return ans
print(proc(N, P))

Solution (Python):
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
mod = 1000000007
m = [(0, 1), (1, 0), (-1, 0), (0, -1)]
inf = float('INF')


def solve():
    n = II()
    p = LI()
    dp = [min(i, j, n - i - 1, n - j - 1) for i in range(n) for j in range(n)]
    c = [1 for i in range(n) for j in range(n)]
    d = defaultdict(tuple)
    for i in range(-1, n + 1):
        for j in range(n):
            d[i * n + j] = (i, j)
    q = [0] * (n ** 2)
    ans = 0
    for pi in p:
        pi -= 1
        ans += dp[pi]
        c[pi] = 0
        q[0] = pi
        p = 0
        l = 1
        while p != l:
            yx = q[p]
            p += 1
            score = dp[yx] + c[yx]
            y, x = d[yx]
            if 0 < y < n - 1:
                if 0 < x < n - 1:
                    myx = yx + n
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx - n
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx - 1
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx + 1
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                else:
                    if x == 0:
                        myx = yx + 1
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
                    elif x == n - 1:
                        myx = yx - 1
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
            else:
                if y == 0:
                    if 0 < x < n - 1:
                        myx = yx + n
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
                elif y == n - 1:
                    if 0 < x < n - 1:
                        myx = yx - n
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
    print(ans)
    return



if __name__ == '__main__':
    solve()

Solution (Python):
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])







@numba.njit("i8(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    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)
    
    Buf = [(0, 0) for _ in range(1<<17)]
    Buf_idx = 0
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        Buf[Buf_idx] = (y, x)
        Buf_idx += 1
        while Buf_idx:
            Buf_idx -= 1
            vy, vx = Buf[Buf_idx]
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            
            for j in range(4):
                uy, ux = vy + Dy[j], vx + Dx[j]
                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
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
                else:
                    if Mat[uy,ux] >= val+2:
                        Mat[uy,ux] = val+1
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
    
    
    return ans
print(proc(N, P))

Solution (Python):
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])







@numba.njit("i8(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    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*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        st = [(y, x)]
        while st:
            vy, vx = st.pop()
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            
            for j in range(4):
                uy, ux = vy + Dy[j], vx + Dx[j]
                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))
    
    
    return ans
print(proc(N, P))

Solution (Python):
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])







@numba.njit("void(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    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*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        st = [(y, x)]
        while st:
            vy, vx = st.pop()
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            
            for j in range(4):
                uy, ux = vy + Dy[j], vx + Dx[j]
                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))
    
    
    print(ans)
proc(N, P)

Solution (Python):
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])







@numba.njit("void(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    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*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        st = [(y, x)]
        while st:
            vy, vx = st.pop()
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            
            for j in range(4):
                dy,dx = Dy[j],Dx[j]
                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))
    
    
    print(ans)
proc(N, P)

Solution (Python):
def main():
    import sys
    import time
    from collections import deque
    input = sys.stdin.readline
    sys.setrecursionlimit(10**6)
    N = int(input())
    P = [int(a) for a in input().strip().split()]
    G = [[min(n, N-n-1,i, N-i-1) for i in range(N)] for n in range(N)]
    Gflag = [[1] * N for _ in range(N)]
    ans = 0

    vecs = [(1, 0), (0, 1), (-1, 0), (0, -1)]

    for p in P:
        row, col = (p-1) // N, (p-1) % N
        ans += G[row][col]
        Gflag[row][col] = 0
        q = deque([(G[row][col], row, col)])
        while q:
            cost, row, col = q.popleft()
            if row > 0:
                if G[row-1][col] > cost + Gflag[row][col]:
                    G[row-1][col] = cost + Gflag[row][col]
                    q.append((cost+Gflag[row][col], row-1, col))
            if row < N-1:
                if G[row+1][col] > cost + Gflag[row][col]:
                    G[row+1][col] = cost + Gflag[row][col]
                    q.append((cost+Gflag[row][col], row+1, col))
            if col > 0:
                if G[row][col-1] > cost + Gflag[row][col]:
                    G[row][col-1] = cost + Gflag[row][col]
                    q.append((cost+Gflag[row][col], row, col-1))
            if col < N-1:
                if G[row][col+1] > cost + Gflag[row][col]:
                    G[row][col+1] = cost + Gflag[row][col]
                    q.append((cost+Gflag[row][col], row, col+1))

    print(ans)
    
if __name__ == '__main__':
    main()

Solution (Python):


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
p = LI()
p = [((i-1)%n, (i-1)//n) for i in p]
ans = 0
dp = [[min(i, j, n - (i + 1), n - (j + 1)) for j in range(n)] for i in range(n)]
dp2 = [[False]*n for _ in range(n)]
for (q, r) in p:
    ans += dp[r][q]
    dp2[r][q] = True
    h = [(dp[r][q], r, q)]
    while h:
        d, y, x = h.pop()
        if not dp2[y][x]:
            d += 1
        if x != 0:
            if dp[y][x-1] > d:
                dp[y][x-1] = d
                h.append((d, y, x-1))
        if x != n-1:
            if dp[y][x+1] > d:
                dp[y][x+1] = d
                h.append((d, y, x+1))
        if y != 0:
            if dp[y-1][x] > d:
                dp[y-1][x] = d
                h.append((d, y-1, x))
        if y != n-1:
            if dp[y+1][x] > d:
                dp[y+1][x] = d
                h.append((d, y+1, x))
print(ans)

Solution (Python):
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])







@numba.njit("void(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    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*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        st = [(y, x)]
        while st:
            vy, vx = st.pop()
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            
            for j in range(4):
                dy = Dy[j]
                dx = Dx[j]
                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))
    
    
    print(ans)
proc(N, P)

Solution (Python):

import sys
input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return map(int,input().split())
def LI(): return list(map(int,input().split()))

def main():
    n = INT()
    P = LI()
    cost = [[min(i, n-i-1, j, n-j-1) for j in range(n)] for i in range(n)]
    issit = [[True for _ in range(n)] for _ in range(n)]
    ans = 0

    for p in P:
        i,j = divmod(p-1,n)
        issit[i][j] = False
        ans += cost[i][j]

        q = [(i, j, cost[i][j])]
        while q:
            n_i, n_j, cur_cost = q.pop()

            if n_i > 0 and cost[n_i-1][n_j] > cur_cost:
                cost[n_i-1][n_j] = cur_cost
                q.append((n_i-1,n_j,cur_cost+issit[n_i-1][n_j]))

            if n_i < n-1 and cost[n_i+1][n_j] > cur_cost:
                cost[n_i+1][n_j] = cur_cost
                q.append((n_i+1,n_j,cur_cost+issit[n_i+1][n_j]))

            if n_j > 0 and cost[n_i][n_j-1] > cur_cost:
                cost[n_i][n_j-1] = cur_cost
                q.append((n_i,n_j-1,cur_cost+issit[n_i][n_j-1]))
 
            if n_j < n-1 and cost[n_i][n_j+1] > cur_cost:
                cost[n_i][n_j+1] = cur_cost
                q.append((n_i,n_j+1,cur_cost+issit[n_i][n_j+1]))
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
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





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(ans)
    
    
    return ans


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


dist = [INF] * len(P)
for h, w in itertools.product(range(N), range(N)):
    dist[h * N + w] = min(h, w, N - h - 1, N - w - 1)
present = [1] * len(P)

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

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

Solution (Python):
import sys
from collections import deque

readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
    n = ni()
    p = nl()
    diag = [-1, 1, n, -n]
    st = [1]*(n+2)**2
    gr = [0]*(n+2)**2
    ans = 0
    for i in range(n):
        for j in range(n):
            gr[i*n + j + n + 1] = min(min(i, j), n-1-max(i, j))
    for v in p:
        v += n
        ans += gr[v]
        st[v] = 0
        c = gr[v]
        for dv in diag:
            nv = v + dv
            c = min(c, gr[nv] + st[nv])
        gr[v]= c
        q = deque()
        q.append(v)
        while q:
            v = q.popleft()
            for dv in diag:
                nv = v + dv
                if gr[nv] > gr[v] + st[v]:
                    gr[nv] = gr[v] + st[v]
                    if st[v]:
                        q.append(nv)
                    else:
                        q.appendleft(nv)
    print(ans)
    return

if __name__ == '__main__':
    solve()

Solution (Python):



import sys
readline = sys.stdin.readline
read = sys.stdin.read

n,*p = map(int,read().split())
N = n*n

dist = [0]*N

for a in range(n):
    for b in range(n):
        dist[a*n+b] = min(a,n-1-a,b,n-1-b)





ans = 0
iru = [1]*N

for pi in p:
    pi -= 1

    ans += dist[pi]
    iru[pi] = 0

    q = [pi]
    
    
    while q:
        
        v = q.pop()
        for i in [-n,-1,1,n]:
            if i==1 and v%n==n-1: continue
            if i==-1 and v%n==0: continue
            nv = v+i
            if 0 <= nv < N and dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        
                    
    

print(ans)