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:
from numba import njit
import numpy as np

@njit('i4, i4, i4, i4[:,:], i4[:,:]', cache=True)
def dfs(N, h, w, minDist, isFilled):
    dist = minDist[h][w] + isFilled[h][w]

    if h + 1 < N and minDist[h + 1][w] > dist:
        minDist[h + 1][w] = dist
        dfs(N, h + 1, w, minDist, isFilled)
    if h - 1 >= 0 and minDist[h - 1][w] > dist:
        minDist[h - 1][w] = dist
        dfs(N, h - 1, w, minDist, isFilled)
    if w + 1 < N and minDist[h][w + 1] > dist:
        minDist[h][w + 1] = dist
        dfs(N, h, w + 1, minDist, isFilled)
    if w - 1 < N and minDist[h][w - 1] > dist:
        minDist[h][w - 1] = dist
        dfs(N, h, w - 1, minDist, isFilled)

@njit('i4(i4, i4[:])', cache=True)
def main(N, P):
    minDist = np.ones((N, N), dtype=np.int32)
    isFilled = np.ones((N, N), dtype=np.int32)

    for h in range(N):
        for w in range(N):
            minDist[h][w] = min(h, N - h - 1, w, N - w - 1)

    ans = 0
    for p in P:
        h, w = divmod(p, N)
        ans += minDist[h][w]
        isFilled[h][w] = False
        dfs(N, h, w, minDist, isFilled)
    return ans

N = int(input())
P = np.asarray(list(map(lambda a: int(a) - 1, input().split())), dtype=np.int32)

print(main(N, P))

Submission status: Runtime Error

Solution code:
from numba import njit
import numpy as np
@njit
def main():
    n=int(input())
    p=list(map(int,input().split()))
    h=[min(i//n,n-i//n-1,i%n,n-i%n-1) for i in range(n**2)]
    h=np.array(h)
    stay=np.full(n**2,1)
    ans=0
    def func(x,c):
        # hを更新
        todo=[[x,c]]
        seen=set(())
        while todo:
            v,c=todo.pop()
            nvs=[v+n,v-n]
            if v%n<n-1:nvs.append(v+1)
            if v%n>0:nvs.append(v-1)
            for nv in nvs:
                if nv<0 or n**2<=nv:continue
                if nv in seen:continue
                if h[nv]>c:
                    h[nv]=c
                    todo.append([nv,c+stay[nv]])
                seen.add(nv)
    for x in p:
        c=h[x-1]
        ans+=c
        stay[x-1]=0
        func(x-1,c)
    print(ans)
    #for i in range(n):
    #    print(h[i*n:(i+1)*n])
if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(4100000)

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

MAP = [[min(i, j, N-i-1, N-j-1) for i in range(N)] for j in range(N)]

d = [[1 for i in range(N)] for j in range(N)]

tx = [1, 0, -1, 0]
ty = [0, 1, 0, -1]

def dfs(x, y, cnt):
    for i in range(4):
        nx = x + tx[i]
        ny = y + ty[i]
        if 0 <= nx < N and 0 <= ny < N and MAP[nx][ny] > MAP[x][y] + d[x][y]:
            MAP[nx][ny] = MAP[x][y] + d[x][y]
            dfs(nx, ny, cnt + d[x][y])

ans = 0

for p in P:
    x = (p-1) // N
    y = (p-1) % N
    d[x][y] = 0
    cnt = float('INF')
    for i in range(4):
        nx = x + tx[i]
        ny = y + ty[i]
        if 0 <= nx < N and 0 <= ny < N:
            cnt = min(cnt, MAP[nx][ny] + d[nx][ny])
        else:
            cnt = min(cnt, 0)
    
    ans += MAP[x][y]
    
    MAP[x][y] = cnt
    
    bfs(x, y, cnt)
    

print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
P = list(map(int,input().split()))

MAP = [[min(i, j, N-i-1, N-j-1) for i in range(N)] for j in range(N)]

d = [[1 for i in range(N)] for j in range(N)]

tx = [1, 0, -1, 0]
ty = [0, 1, 0, -1]

def bfs(x, y, cnt):
    for i in range(4):
        nx = x + tx[i]
        ny = y + ty[i]
        if 0 <= nx < N and 0 <= ny < N and MAP[nx][ny] > MAP[x][y] + d[x][y]:
            MAP[nx][ny] = MAP[x][y] + d[x][y]
            bfs(nx, ny, cnt + d[x][y])

ans = 0

for p in P:
    x = (p-1) // N
    y = (p-1) % N
    d[x][y] = 0
    cnt = float('INF')
    for i in range(4):
        nx = x + tx[i]
        ny = y + ty[i]
        if 0 <= nx < N and 0 <= ny < N:
            cnt = min(cnt, MAP[nx][ny] + d[nx][ny])
        else:
            cnt = min(cnt, 0)
    
    ans += MAP[x][y]
    
    MAP[x][y] = cnt
    
    bfs(x, y, cnt)
    

print(ans)

Submission status: Runtime Error

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
import time
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
#    n = 500
    cos = [[min(i,j,n-1-i,n-1-j) for i in range(n)] for j in range(n)]
#    p = [(i//n,i%n) for i in range(n**2)]
    p = [((int(i)-1)//n,((int(i)-1)%n) for i in ipt().split()]
    ans = 0
    q = []
    al = [[True]*n for i in range(n)]

    for px,py in p:
        ans += cos[px][py]
        q.append((px,py,cos[px][py]))
        al[px][py] = False
        while q:
            qx,qy,qc = q.pop()
            if qx != 0 and cos[qx-1][qy] > qc:
                cos[qx-1][qy] = qc
                q.append((qx-1,qy,qc+al[qx-1][qy]))
            if qx != n-1 and cos[qx+1][qy] > qc:
                cos[qx+1][qy] = qc
                q.append((qx+1,qy,qc+al[qx+1][qy]))
            if qy != 0 and cos[qx][qy-1] > qc:
                cos[qx][qy-1] = qc
                q.append((qx,qy-1,qc+al[qx][qy-1]))
            if qy != n-1 and cos[qx][qy+1] > qc:
                cos[qx][qy+1] = qc
                q.append((qx,qy+1,qc+al[qx][qy+1]))

    print(ans)

    return

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import deque
def dfs(x,y):
    z = h[y][x] + grid[y][x]
    for i in range(4):
        next_x = x+dx[i]
        next_y = y+dy[i]
        if h[next_y][next_x] > z:
            h[next_y][next_x] = z
            dfs(next_x,next_y)
n = int(input())
h = [[0]*(n+2) for _ in range(n+2)]
for i in range(1,n+1):
    for j in range(1,n+1):
        h[i][j] = min(i,n-i+1,j,n-j+1)-1
grid = [[1]*(n+1) for _ in range(n+1)]
dx = [0,1,0,-1]
dy = [1,0,-1,0]
ans = 0
p = list(map(int,input().split()))
for i in range(n**2):
    pos = p[i]
    x = (pos-1)%n+1
    y = (pos-1)//n+1
    ans += h[y][x]
    grid[y][x] = 0
    dfs(x,y)
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(100000)

from numba import njit

@njit('(i4,i4[:],i4[:],i4[:])',cache=True)
def main(n,p,dx,dy):
    ans = 0
    def dfs(x,y,dx,dy,grid,dis):
        z = dis[y][x] + grid[y][x]
        for i in range(4):
            next_x = x+dx[i]
            next_y = y+dy[i]
            if dis[next_y][next_x] > z:
                dis[next_y][next_x] = z
                dfs(next_x,next_y,dx,dy,grid,dis)
    grid = np.ones((n+1,n+1),np.int32)
    dis = np.zeros((n+2,n+2),np.int32)
    for i in range(1,n+1):
        for j in range(1,n+1):
            dis[i][j] = min(i,n-i+1,j,n-j+1)-1
    for i in range(n**2):
        pos = p[i]
        x = (pos-1)%n+1
        y = (pos-1)//n+1
        ans += dis[y][x]
        grid[y][x] = 0
        dfs(x,y,dx,dy,grid,dis)
    return ans

n = int(readline())
p = np.array(readline().split(),np.int32)
dx = np.array([0,1,0,-1])
dy = np.array([1,0,-1,0])
print(main(n,p,dx,dy))

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(100000)

from numba import njit

@njit('(i4,i4[:])',cache=True)
def main(n,p):
    dx = np.array([0,1,0,-1])
    dy = np.array([1,0,-1,0])
    ans = 0
    def dfs(x,y,dx,dy,grid,dis):
        z = dis[y][x] + grid[y][x]
        for i in range(4):
            next_x = x+dx[i]
            next_y = y+dy[i]
            if dis[next_y][next_x] > z:
                dis[next_y][next_x] = z
                dfs(next_x,next_y,dx,dy,grid,dis)
    grid = np.ones((n+1,n+1),np.int32)
    dis = np.zeros((n+2,n+2),np.int32)
    for i in range(1,n+1):
        for j in range(1,n+1):
            dis[i][j] = min(i,n-i+1,j,n-j+1)-1
    for i in range(n**2):
        pos = p[i]
        x = (pos-1)%n+1
        y = (pos-1)//n+1
        ans += dis[y][x]
        grid[y][x] = 0
        dfs(x,y,dx,dy,grid,dis)
    return ans

n = int(readline())
p = np.array(readline().split(),np.int32)
print(main(n,p))

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(100000)

from numba import njit

@njit('i4,i4[:]',cache=True)
def main(n,p):
    dx = np.array([0,1,0,-1])
    dy = np.array([1,0,-1,0])
    ans = 0
    def dfs(x,y,dx,dy,grid,dis):
        z = dis[y][x] + grid[y][x]
        for i in range(4):
            next_x = x+dx[i]
            next_y = y+dy[i]
            if dis[next_y][next_x] > z:
                dis[next_y][next_x] = z
                dfs(next_x,next_y,dx,dy,grid,dis)
    grid = np.ones((n+1,n+1),np.int32)
    dis = np.zeros((n+2,n+2),np.int32)
    for i in range(1,n+1):
        for j in range(1,n+1):
            dis[i][j] = min(i,n-i+1,j,n-j+1)-1
    for i in range(n**2):
        pos = p[i]
        x = (pos-1)%n+1
        y = (pos-1)//n+1
        ans += dis[y][x]
        grid[y][x] = 0
        dfs(x,y,dx,dy,grid,dis)
    return ans

n = int(readline())
p = np.array(readline().split(),np.int32)
print(main(n,p))

Submission status: Runtime Error

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

def main(n,p):
    dx = np.array([0,1,0,-1])
    dy = np.array([1,0,-1,0])
    ans = 0
    def dfs(x,y,dx,dy,grid,dis):
        z = dis[y][x] + grid[y][x]
        for i in range(4):
            next_x = x+dx[i]
            next_y = y+dy[i]
            if dis[next_y][next_x] > z:
                dis[next_y][next_x] = z
                dfs(next_x,next_y,dx,dy,grid,dis)
    grid = np.ones((n+1,n+1),np.int32)
    dis = np.zeros((n+2,n+2),np.int32)
    for i in range(1,n+1):
        for j in range(1,n+1):
            dis[i][j] = min(i,n-i+1,j,n-j+1)-1
    for i in range(n**2):
        pos = p[i]
        x = (pos-1)%n+1
        y = (pos-1)//n+1
        ans += dis[y][x]
        grid[y][x] = 0
        dfs(x,y,dx,dy,grid,dis)
    return ans

n = int(readline())
p = np.array(readline().split(),np.int32)
print(main(n,p))

Submission status: Runtime Error

Solution code:
def initDistanceTable(n):
    DistanceMap = [1] * (n * n)
    for x in range(n):
        for y in range(n):
            DistanceMap[x + y * n] = getShortest(x, y, n)
    return DistanceMap

def removeTargetSub(PersonMap, DistanceMap, FlagMap, x, y, dx, dy, index, n):
    if x + dx < 0 or x + dx >= n or y + dy < 0 or y + dy >= n:
        return
    t1 = x + n * y
    t2 = x + dx + n * (y + dy)
    if FlagMap[t2] < index:
        if DistanceMap[t1] + 1 == DistanceMap[t2] and PersonMap[t2] < index:
            removeTarget(PersonMap, DistanceMap, FlagMap, x + dx, y + dy, index, n)
            return
        if DistanceMap[t1] + 2 == DistanceMap[t2] and PersonMap[t2] > index:
            removeTarget(PersonMap, DistanceMap, FlagMap, x + dx, y + dy, index, n)
            return

def removeTarget(PersonMap, DistanceMap, FlagMap, x, y, index, n):
    t = x + n * y
    DistanceMap[t] -= 1
    FlagMap[t] = index
    removeTargetSub(PersonMap, DistanceMap, FlagMap, x, y, -1, 0, index, n)
    removeTargetSub(PersonMap, DistanceMap, FlagMap, x, y, 1, 0, index, n)
    removeTargetSub(PersonMap, DistanceMap, FlagMap, x, y, 0, -1, index, n)
    removeTargetSub(PersonMap, DistanceMap, FlagMap, x, y, 0, 1, index, n)

def getShortest(x, y, n):
    return min([x, n - 1 - x, y, n - 1 - y]) + 1


def main():
    ans = 0
    n = int(input())
    seq = list(map(int,input().split()))
    PersonMap = [0] * (n * n)
    FlagMap = [-1] * (n * n)
    for i in range(n*n):
        PersonMap[seq[i] - 1] = i

    DistanceMap = initDistanceTable(n)
    for i in range(n*n):
        ans = ans + DistanceMap[seq[i] - 1] - 1
        removeTarget(PersonMap, DistanceMap, FlagMap, (seq[i] - 1) % n, (seq[i] - 1) // n, i, n)

    print(ans)

main()

Submission status: Runtime Error

Solution code:
from collections import deque
import copy
f = open("C:/Users/naoki/Desktop/Atcoder/input.txt") 

n = int(f.readline())
p = list(map(int, f.readline().split()))
for i in range(len(p)):
    p[i] -= 1

to_outsides = [[0 for _ in range(n)] for _ in range(n)]
not_exist = [["■" for _ in range(n)] for _ in range(n)]


for i in range(n):
    for j in range(n):
        to_outside = [i,n-1-i,j,n-1-j]
        to_outsides[i][j] = min(to_outside)

directions = [[-1,0],[1,0],[0,-1],[0,1]]

all_loss = 0
answer = 0
for i, person in enumerate(p):
    exited = [person//n, person%n]
    answer += to_outsides[exited[0]][exited[1]]
    not_exist[exited[0]][exited[1]] = "□"
    seen = []
    seen.append([exited[0],exited[1]])
    todo = deque([exited])
    renews = []
    while len(todo)>0:
        now = todo.pop()
        renews.append(now)
        for direction in directions:
            try:
                checking = [now[0]+direction[0],now[1]+direction[1]]
                to_outsides[checking[0]][checking[1]]
            except:
                continue
            if [checking[0],checking[1]] not in seen:
                if ((not_exist[checking[0]][checking[1]] == "□" and  to_outsides[checking[0]][checking[1]]==to_outsides[now[0]][now[1]])or\
                 to_outsides[checking[0]][checking[1]]>to_outsides[now[0]][now[1]]):
                    todo.append([checking[0],checking[1]])
                    seen.append([checking[0],checking[1]])
                else:
                    seen.append([checking[0],checking[1]])
                    
    for renew in renews:
        if to_outsides[renew[0]][renew[1]] != 0:
            to_outsides[renew[0]][renew[1]]-=1
print(answer)

Submission status: Runtime Error

Solution code:
from collections import deque
import copy

n = int(input())
p = list(map(int, input()))
for i in range(len(p)):
    p[i] -= 1

to_outsides = [[0 for _ in range(n)] for _ in range(n)]
not_exist = [["■" for _ in range(n)] for _ in range(n)]


for i in range(n):
    for j in range(n):
        to_outside = [i,n-1-i,j,n-1-j]
        to_outsides[i][j] = min(to_outside)

directions = [[-1,0],[1,0],[0,-1],[0,1]]

all_loss = 0
answer = 0
for i, person in enumerate(p):
    exited = [person//n, person%n]
    answer += to_outsides[exited[0]][exited[1]]
    not_exist[exited[0]][exited[1]] = "□"
    seen = []
    seen.append([exited[0],exited[1]])
    todo = deque([exited])
    renews = []
    while len(todo)>0:
        now = todo.pop()
        renews.append(now)
        for direction in directions:
            try:
                checking = [now[0]+direction[0],now[1]+direction[1]]
                to_outsides[checking[0]][checking[1]]
            except:
                continue
            if [checking[0],checking[1]] not in seen and\
            ((not_exist[checking[0]][checking[1]] == "□" and  to_outsides[checking[0]][checking[1]]==to_outsides[now[0]][now[1]])or\
            to_outsides[checking[0]][checking[1]]>to_outsides[now[0]][now[1]]):
                todo.append([checking[0],checking[1]])
                seen.append([checking[0],checking[1]])
    
    for renew in renews:
        if to_outsides[renew[0]][renew[1]] != 0:
            to_outsides[renew[0]][renew[1]]-=1
print(answer)

Submission status: Runtime Error

Solution code:
from collections import deque
import copy
f = open("C:/Users/naoki/Desktop/Atcoder/input.txt") 

n = int(f.readline())
p = list(map(int, f.readline().split()))
for i in range(len(p)):
    p[i] -= 1

to_outsides = [[0 for _ in range(n)] for _ in range(n)]
not_exist = [["■" for _ in range(n)] for _ in range(n)]


for i in range(n):
    for j in range(n):
        to_outside = [i,n-1-i,j,n-1-j]
        to_outsides[i][j] = min(to_outside)

directions = [[-1,0],[1,0],[0,-1],[0,1]]

all_loss = 0
answer = 0
for i, person in enumerate(p):
    to_outsides_pre = copy.deepcopy(to_outsides)    
    exited = [person//n, person%n]
    answer += to_outsides[exited[0]][exited[1]]
    not_exist[exited[0]][exited[1]] = "□"
    seen = []
    seen.append([exited[0],exited[1]])
    todo = deque([exited])
    renews = []
    while len(todo)>0:
        now = todo.pop()
        renews.append(now)
        for direction in directions:
            try:
                checking = [now[0]+direction[0],now[1]+direction[1]]
                to_outsides[checking[0]][checking[1]]
            except:
                continue
            if [checking[0],checking[1]] not in seen and\
            ((not_exist[checking[0]][checking[1]] == "□" and  to_outsides[checking[0]][checking[1]]==to_outsides[now[0]][now[1]])or\
            to_outsides[checking[0]][checking[1]]>to_outsides[now[0]][now[1]]):
                todo.append([checking[0],checking[1]])
                seen.append([checking[0],checking[1]])
    
    for renew in renews:
        if to_outsides[renew[0]][renew[1]] != 0:
            to_outsides[renew[0]][renew[1]]-=1
print(answer)

Submission status: Runtime Error

Solution code:
from collections import deque

f = open("C:/Users/naoki/Desktop/Atcoder/input.txt") 

n = int(f.readline())
p = list(map(int, f.readline().split()))
for i in range(len(p)):
    p[i] -= 1

to_outsides = [[0 for _ in range(n)] for _ in range(n)]
not_exist = [["■" for _ in range(n)] for _ in range(n)]


for i in range(n):
    for j in range(n):
        to_outside = [i,n-1-i,j,n-1-j]
        to_outsides[i][j] = min(to_outside)

directions = [[-1,0],[1,0],[0,-1],[0,1]]


all_loss = 0
answer = 0
for i, person in enumerate(p):
    
    exited = [person//n, person%n]
    answer += to_outsides[exited[0]][exited[1]]
    not_exist[exited[0]][exited[1]] = "□"
    seen = [[False for _ in range(n)] for _ in range(n)]
    seen[exited[0]][exited[1]]=True
    todo = deque([exited])
    renews = []
    while len(todo)>0:
        now = todo.pop()
        renews.append(now)
        for direction in directions:
            try:
                checking = [now[0]+direction[0],now[1]+direction[1]]
                to_outsides[checking[0]][checking[1]]
            except:
                continue
            if seen[checking[0]][checking[1]] == False and\
            ((not_exist[checking[0]][checking[1]] == "□" and  to_outsides[checking[0]][checking[1]]==to_outsides[now[0]][now[1]])or\
            to_outsides[checking[0]][checking[1]]>to_outsides[now[0]][now[1]]):
                todo.append([checking[0],checking[1]])
                seen[checking[0]][checking[1]] = True
    to_outsides_pre = to_outsides.copy()
    for renew in renews:
        if to_outsides[renew[0]][renew[1]] != 0:
            to_outsides[renew[0]][renew[1]]-=1
print(answer)

Submission status: Runtime Error

Solution code:
from numba import njit

@njit('(i4,i4,i4[::1],i4[::1],i4[::1])', cache=True)
def calc(N, M, A, X, Y):
    ans = 0
    for a in A:
        aa = (a // N + 1) * M + a % N + 1
        ans += X[aa]
        h = X[aa]
        if h < 0: continue
        Q = [(aa, h)]
        q = 0
        X[aa] -= 1
        Y[aa] = 0
        dd = (-1, 1, M, -M)
        while q < len(Q):
            i, h = Q[q]
            q += 1
            for d in dd:
                j = i + d
                y = Y[j]
                if X[j] >= h + y:
                    X[j] -= 1
                    Q.append((j, h + y))
    return ans

N = int(input())
A = [int(a)-1 for a in input().split()]
M = N + 2
X = [max(min(i-1, j-1, M-2-i, M-2-j), -1) for j in range(M) for i in range(M)]
Y = [min(x, 0) + 1 for x in X]
print(calc(N, M, A, X, Y))

Submission status: Runtime Error

Solution code:
from numba import njit

@njit('(i4,i4,i4[::-1],i4[::-1],i4[::-1])', cache=True)
def calc(N, M, A, X, Y):
    ans = 0
    for a in A:
        aa = (a // N + 1) * M + a % N + 1
        ans += X[aa]
        h = X[aa]
        if h < 0: continue
        Q = [(aa, h)]
        q = 0
        X[aa] -= 1
        Y[aa] = 0
        dd = (-1, 1, M, -M)
        while q < len(Q):
            i, h = Q[q]
            q += 1
            for d in dd:
                j = i + d
                y = Y[j]
                if X[j] >= h + y:
                    X[j] -= 1
                    Q.append((j, h + y))
    return ans

N = int(input())
A = [int(a)-1 for a in input().split()]
M = N + 2
X = [max(min(i-1, j-1, M-2-i, M-2-j), -1) for j in range(M) for i in range(M)]
Y = [min(x, 0) + 1 for x in X]
print(calc(N, M, A, X, Y))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
import numba

@njit
n = int(input())
a = list(map(int,input().split()))
n += 2
ls = [0 for i in range(n*n)]
for i in range(n):
  for j in range(n):
    ls[i*n+j] = min(i,j,n-1-i,n-1-j)-1
ans = 0
st = [0]*(n*n)
for i in a:
  x,y = divmod(i-1,n-2)
  i = (x+1)*n+(y+1)
  ans += ls[i]
  st[i]=1
  q = deque([i])
  while q:
    j = q.popleft()
    for k in (j-n,j+n,j+1,j-1):
      if st[j]:
        if ls[j] < ls[k]:
          ls[k] = ls[j]
          q.append(k)
      elif ls[j]+1 < ls[k]:
        ls[k] = ls[j]+1
        q.append(k)
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
[n], *e = [[*map(int, t.split())] for t in open(0)]


viewers = set(range(1, n**2 + 1))
mem = {x: min((x - 1) % n, (n - x) % n, (x - 1)//n, n - 1 - (x - 1)//n)
       for x in range(1, n**2 + 1)}

ans = 0


def directions(x):
    tmp = []
    if x % n != 1:
        tmp.append(x - 1)
    if x % n > 0:
        tmp.append(x + 1)
    if (x - 1)//n > 0:
        tmp.append(x - n)
    if (x - 1)//n < n - 1:
        tmp.append(x + n)
    return tmp


for x in e[0]:
    @np.jit
    def bfs(x):
        queue = [x]
        while queue:
            tmp = queue.pop(0)
            z = mem[tmp] + (tmp in viewers)
            for k in directions(tmp):
                if mem[k] > z:
                    mem[k] = z
                    queue.append(k)

    ans += mem[x]
    viewers.remove(x)
    bfs(x)

print(ans)

Submission status: Runtime Error

Solution code:
n = int(input())
p = list(map(int,input().split()))

thtr = [0]*((n+2)**2)
tpsn = [0]*((n+2)**2)
psn = [1]*(n**2)

def ppidx(ttidx):
    r = ttidx // (n+2) - 1
    c = ttidx % (n+2) - 1
    if r == 0 or r >= n:
        return -1
    if c== 0 or c >= n:
        return -1
    return n*r + c

def ttidx(psidx):
    r = psidx // n
    c = psidx %  n
    return (n+2)*(r+1) + c + 1

def init_rnk(psidx):
    r = psidx // n
    c = psidx %  n
    return(min(r,c,n-1-r,n-1-c)+1)

def get_cst(tidx,h):
    if thtr[tidx]==0:
        return 0

    if tidx in h:
        return 99

    h.add(tidx)

    wk = min( get_cst(tidx-1,h)   + tpsn[tidx-1]\
             ,get_cst(tidx+1,h)   + tpsn[tidx+1]\
             ,get_cst(tidx-n-2,h) + tpsn[tidx-n-2]\
             ,get_cst(tidx+n+2,h) + tpsn[tidx+n+2])

    if wk == 0:
        thtr[tidx] = 0

    return wk

#初期化
for i in range(n**2):
    tpsn[ttidx(i)] = 1
    thtr[ttidx(i)] = 1

#処理
ans = 0
for el in p:
    psn[el-1]=0
    tpsn[ttidx(el-1)]=0
    h = set()
    wk = get_cst(ttidx(el-1),h)
    ans += wk

print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(20000)
[n], *e = [[*map(int, t.split())] for t in open(0)]


viewers = set(range(1, n**2 + 1))
mem = {x: min((x - 1) % n, (n - x) % n, (x - 1)//n, n - 1 - (x - 1)//n) for x in range(1, n**2 + 1)}

ans = 0

def directions(x):
    tmp = []
    if x % n != 1:
        tmp.append(x - 1)
    if x % n > 0:
        tmp.append(x + 1)
    if (x - 1)//n > 0:
        tmp.append(x - n)
    if (x - 1)//n < n - 1:
        tmp.append(x + n)
    return tmp


for x in e[0]:

    def fill(x):
        z = mem[x] + (x in viewers)
        for k in directions(x):
            if mem[k] > z:
                mem[k] = z
                fill(k)

    ans += mem[x]
    viewers.remove(x)
    fill(x)

print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
n = int(input())
Ps = list(map(lambda x: int(x)-1, input().split()))
cost = [min(i, n-1-i, j, n-1-j) for i in range(n) for j in range(n)]
DIRC = [(-1, 0), (0, 1), (1, 0), (0, -1)]
exist = [1]*(n**2)


def to_idx(p):
    return divmod(p, n)


def to_v(i, j):
    return i*n+j


def bfs(init_v):
    next_v = deque([init_v])
    exist[init_v] = 0
    while next_v:
        v = next_v.popleft()
        i, j = to_idx(v)
        for di, dj in DIRC:
            x, y = i+di, j+dj
            if x < 0 or y < 0 or n <= x or n <= y:
                continue
            c = cost[v]+exist[v]
            if cost[to_v(x, y)] <= c:
                continue
            cost[to_v(x, y)] = c
            next_v.append((x, y))


ans = 0
for p in Ps:
    ans += cost[p]
    bfs(p)
print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
from collections import deque
from numba import njit


@njit('(i4,i4[::1])', cache=True)
def solve(N, ps):

    sheets = np.ndarray(shape=(N, N), dtype=int)

    for i in range(N):
        rmax = min(i, N-1-i)
        sheets[i] = np.array([min(j, N-1-j, rmax) for j in range(N)])

    total = 0
    q = deque()

    def push(q, x, y, v, passed):
        for px, py in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:
            if (px, py) in passed:
                continue
            if px < 0 or N <= px or py < 0 or N <= py:
                continue
            passed.add((px, py))
            q.append((px, py, v))

    for p in ps:
        y, x = divmod(p-1, N)
        v = sheets[x][y]
        total += v
        sheets[x][y] = -1

        passed = {(x, y)}
        push(q, x, y, v, passed)

        while q:
            x, y, v = q.popleft()
            sv = sheets[x][y]
            if sv == -1:
                push(q, x, y, v, passed)
            elif v < sv:
                sheets[x][y] = v
                push(q, x, y, v+1, passed)

    return total


def main():
    N = int(input())
    ps = map(int, input().split())
    print(solve(N, ps))


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys

# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.buffer.read
from heapq import heappop, heappush
from collections import defaultdict

sys.setrecursionlimit(10 ** 7)
# import math
# from itertools import product, accumulate, combinations, product
# import bisect# lower_bound etc
import numpy as np
# from copy import deepcopy
from collections import deque
import numba

N = int(input())
P = np.array(list(map(int, sysread().split())))
@numba.njit("void(i8,i8[:])")
def run():
    seats = np.zeros((N,N), dtype=np.int32)
    seen = np.zeros((N,N), dtype=np.int32)  # there is a person : 1
    up, down = 0, N - 1
    dist = 0
    while True:
        seats[up, up:down+1] = dist
        seats[down, up:down+1] = dist
        seats[up:down+1, up] = dist
        seats[up:down+1, down] = dist
        up += 1
        down -= 1
        dist += 1
        if up > down:
            break

    ret = 0
    ###
    for i in range(N ** 2):
        # print(seats)
        cur_i, cur_j = (P[i] - 1) // N, (P[i] - 1) % N
        ret += seats[cur_i,cur_j]
        seen[cur_i,cur_j] = 1
        stack = [(seats[cur_i,cur_j], (cur_i, cur_j))]
        while stack:
            del_val, (cur_i, cur_j) = stack.pop()
            for i, j in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                n_i = cur_i + i
                n_j = cur_j + j
                if 0 <= n_i <= N - 1 and 0 <= n_j <= N - 1:
                    if seen[cur_i, cur_j]:
                        if del_val < seats[n_i, n_j]:
                            seats[n_i, n_j] = del_val
                            stack.append((del_val, (n_i, n_j)))
                    else:
                        if del_val + 1 < seats[n_i, n_j]:
                            seats[n_i, n_j] = del_val + 1
                            stack.append((del_val, (n_i, n_j)))

    print(ret)


if __name__ == "__main__":
    run()