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:
# 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

@numba.njit("void(i8,i8[:])")
def run():
    N = int(input())
    P = np.array(list(map(int, sysread().split())))
    seats = np.array([[0] * N for _ in range(N)])
    seen = np.array([[0] * N for _ in range(N)])  # there is a person : 1
    up, down = 0, N - 1
    dist = 0
    while True:
        for i in range(up, down + 1):
            seats[up][i] = dist
            seats[down][i] = dist
            seats[i][up] = dist
            seats[i][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 = deque([(seats[cur_i,cur_j], (cur_i, cur_j))])
        while stack:
            del_val, (cur_i, cur_j) = stack.popleft()
            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()

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

def run():
    N = int(input())
    P = np.array((list(map(int, sysread().split()))))
    P -= 1

    @numba.njit(parallel=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)
        # print(Mat)
        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 dy, dx in zip(Dy, Dx):
                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))
        # for m in Mat:
        #     print(m)
        print(ans)

    proc(N, P)


if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
from numba import njit
import numpy as np


def main(N, P):
    lista = [1, -1, N, -N]
    d = np.zeros((N, N), dtype=np.int32)
    d = d.ravel()
    sit = np.ones_like(d)
    stack = np.empty_like(d)
    count = 0
    for i in range(N*N):
        d[i] = min(i % N, (N-1-i) % N, i//N, N-1-i//N)
    for player in P:
        sit[player-1] = 0
        count += d[player-1]
        stack[0] = player
        num = 0
        while num >= 0:
            p = stack[num]
            num -= 1
            a = d[p-1]+sit[p-1]
            for i in lista:
                if p+i < 1 or p + i > N*N:
                    continue
                if d[p+i-1] > a:
                    d[p+i-1] = a
                    num += 1
                    stack[num] = p+i
    print(count)


def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i8,i8[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    from my_module import main
    N = int(input())
    P = np.array(input().split(), np.int32)
    #N = 500
    #P = [(i+4000) % N*N for i in range(N*N)]
    main(N, P)

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

def run():
    N = int(input())
    P = list(map(int, sysread().split()))
    seats = [[0] * N for _ in range(N)]
    seen = [[0] * N for _ in range(N)]# there is a person : 1
    left, right, up, down = 0, N-1, 0, N-1
    dist = 0
    while True:
        for i in range(left, right+1):
            seats[up][i] = dist
            seats[down][i] = dist
        for i in range(up, down+1):
            seats[i][left] = dist
            seats[i][right] = dist
        left += 1
        right -= 1
        up += 1
        down -= 1
        dist+= 1
        if left > right or up > down:
            break

    ret = 0
    ###
    for i in range(N**2):
        #print(seats)
        way = {}
        cur_i, cur_j = (P[i] - 1) // N, (P[i] - 1) % N
        ret += seats[cur_i][cur_j]
        seen[cur_i][cur_j] = 1
        del_val = seats[cur_i][cur_j]
        stack = deque([(del_val, (cur_i, cur_j))])

        while stack:
            del_val, (cur_i,cur_j) = stack.popleft()
            way[cur_i * N + cur_j] = 0
            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 and n_i * N + n_j not in way.keys():
                    if del_val < seats[n_i][n_j]:
                        seats[n_i][n_j] = del_val
                        stack.append((del_val + 1, (n_i, n_j)))
                    elif seen[n_i][n_j]:
                        stack.append((del_val, (n_i, n_j)))

    print(ret)


if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
from numba import njit
import numpy as np


def cc_export():
    @njit('(i8, i8[:, :], b1[:], i8[:], i8)')
    def update(n, que, there, cost, pos):
        l = 0
        i = 0

        que[l, 0] = pos
        que[l, 1] = cost[pos] - 1
        # que[l] = pos, cost[pos] - 1
        l += 1

        while i < l:
            pos, dist = que[i]
            i += 1

            if cost[pos] <= dist:
                continue

            y, x = pos // n, pos % n
            cost[pos] = dist

            if y >= 1:
                pp = (y - 1) * n + x
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if y <= n - 2:
                pp = (y + 1) * n + x
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if x >= 1:
                pp = y * n + (x - 1)
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if x <= n - 2:
                pp = y * n + (x + 1)
                cc = int(there[pp])
                que[l] = (pp, dist + cc)
                l += 1

    @njit('(i8, i8[:])')
    def main(n, p):
        que = np.zeros((n * n, 2), dtype=np.int64)
        there = np.full(n * n, True)
        cost = np.array([
            min(i, n - i - 1, j, n - j - 1) for j in range(n) for i in range(n)
        ],
                        dtype=np.int64)

        ans = 0
        for pos in p:
            ans += cost[pos]
            there[pos] = False
            update(n, que, there, cost, pos)
        return ans

    from numba.pycc import CC
    cc = CC('solution')
    cc.export('update', '(i8, i8[:, :], b1[:], i8[:], i8)')(update)
    cc.export('main', '(i8, i8[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        sys.exit(0)

    from solution import update, main
    n = int(input())
    p = np.array(list(map(lambda x: int(x) - 1,
                          input().split())),
                 dtype=np.int64)
    print(main(n, p))

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


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


ans = 0

for x in e[0]:

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

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

print(ans)

Submission status: Runtime Error

Solution code:
from numba import njit
import numpy as np


def main(N, P):
    lista = [1, -1, N, -N]
    d = np.zeros((N, N), dtype=np.int32)
    d = d.ravel()
    sit = np.ones_like(d)
    que = []
    count = 0
    for i in range(N*N):
        d[i] = min(i % N, (N-1-i) % N, i//N, N-1-i//N)
    for player in P:
        sit[player-1] = 0
        count += d[player-1]
        que.append(player)
        for p in que:
            for i in lista:
                if p+i < 1 or p + i > N*N:
                    continue
                if d[p-1]+sit[p-1] < d[p+i-1]:
                    d[p+i-1] = d[p-1]+sit[p-1]
                    que.append(player+i)
    print(count)


def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i8,i8[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    from my_module import main
    N = int(input())
    P = list(map(int, input().split()))
    main(N, P)

Submission status: Runtime Error

Solution code:
from numba import njit
import numpy as np


def main(N, P):
    d = np.zeros((N, N), dtype=np.int32)
    d = d.ravel()
    sit = np.ones_like(d)
    que = []
    count = 0
    for i in range(N*N):
        d[i] = min(i % N, (N-1-i) % N, i//N, N-1-i//N)
    for player in P:
        sit[player-1] = 0
        count += d[player-1]
        que.append(player)
        for p in que:
            for i in (1, -1, N, -N):
                if p+i < 1 or p + i > N*N:
                    continue
                if d[p-1]+sit[p-1] < d[p+i-1]:
                    d[p+i-1] = d[p-1]+sit[p-1]
                    que.append(player+i)
    print(count)


def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i8,i8[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    from my_module import main
    N = int(input())
    P = list(map(int, input().split()))
    main(N, P)

Submission status: Runtime Error

Solution code:
from numba import njit
import numpy as np


def main(N, P):
    d = np.zeros((N, N), dtype=np.int32)
    d = d.ravel()
    sit = np.ones_like(d)
    que = []
    count = 0
    for i in range(N*N):
        d[i] = min(i % N, (N-1-i) % N, i//N, N-1-i//N)
    for player in P:
        sit[player-1] = 0
        count += d[player-1]
        que.append(player)
        for p in que:
            for i in (1, -1, N, -N):
                if p+i < 1 or p + i > N*N:
                    continue
                if d[p-1]+sit[p-1] < d[p+i-1]:
                    d[p+i-1] = d[p-1]+sit[p-1]
                    que.append(player+i)
    print(count)


def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', 'i8,i8[:]')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    from my_module import main
    N = int(input())
    P = list(map(int, input().split()))
    main(N, P)

Submission status: Runtime Error

Solution code:
from numba import njit
import numpy as np


def main(N, P):
    d = np.zeros((N, N), dtype=np.int32)
    d = d.ravel()
    sit = np.ones_like(d)
    que = []
    count = 0
    for i in range(N*N):
        d[i] = min(i % N, (N-1-i) % N, i//N, N-1-i//N)
    for player in P:
        sit[player-1] = 0
        count += d[player-1]
        que.append(player)
        for p in que:
            for i in (1, -1, N, -N):
                if p+i < 1 or p + i > N*N:
                    continue
                if d[p-1]+sit[p-1] < d[p+i-1]:
                    d[p+i-1] = d[p-1]+sit[p-1]
                    que.append(player+i)
    print(count)


def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', 'i8,i8[:]')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    from my_module import main
    N = int(input())
    P = map(int, input().split())
    main(N, P)

Submission status: Runtime Error

Solution code:
[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)}


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


ans = 0

for x in e[0]:

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

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

print(ans)

Submission status: Runtime Error

Solution code:
[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)}


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


ans = 0

for x in e[0]:

    def fill(x):
        for k in directions(x):
            if mem[k] > mem[x]:
                mem[k] = mem[x]
                if k not in viewers:
                    fill(k)
            elif mem[k] == mem[x] and k not in viewers:
                fill(k)

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

print(ans)

Submission status: Runtime Error

Solution code:
[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)}


def directions(x): return [d for d in [
    x - 1, x + 1, x - n, x + n] if 0 < d < n**2 + 1]


ans = 0 

for x in e[0]:

    def fill(x):
        for k in directions(x):
            if mem[k] > mem[x]:
                mem[k] = mem[x]
                if k not in viewers:
                    fill(k)
    ans += mem[x]
    viewers.remove(x)
    fill(x)

print(ans)

Submission status: Runtime Error

Solution code:
[n], *e = [[*map(int, t.split())] for t in open(0)]
viewers = set(range(1, n**2 + 1))
ans = 0

for x in e[0]:
    visited = set()
    clear = {x for x in range(1, n**2 + 1) if x %
             n == 0 or x % n == 1 or x <= n or x > n**2 - n}

    def solve(x):
        if x not in clear:
            visited.add(x)
            tmp = n
            for k in [x - 1, x + 1, x - n, x + n]:
                if tmp == 0:
                    clear.add(x)
                    break
                elif tmp == 1 and k in viewers:
                    continue
                else:
                    if k not in visited:
                        tmp = min(tmp, (k in viewers) + solve(k))
            visited.remove(x)
            return tmp
        return 0

    ans += solve(x)
    viewers.remove(x)

print(ans)

Submission status: Runtime Error

Solution code:
[n], *e = [[*map(int, t.split())] for t in open(0)]
viewers = set(range(1, n**2 + 1))
ans = 0

for x in e[0]:
    visited = set()
    clear = {x for x in range(1, n**2 + 1) if x %
             n == 0 or x % n == 1 or x <= n or x > n**2 - n}

    def solve(x):
        if x not in clear:
            visited.add(x)
            tmp = n
            for k in [x - 1, x + 1, x - n, x + n]:
                if tmp == 0:
                    clear.add(x)
                    break
                else:
                    if k not in visited:
                        tmp = min(tmp, (k in viewers) + solve(k))
            visited.remove(x)
            return tmp
        return 0

    ans += solve(x)
    viewers.remove(x)

print(ans)

Submission status: Runtime Error

Solution code:
[n], *e = [[*map(int, t.split())] for t in open(0)]
viewers = set(range(1, n**2 + 1))
ans = 0

for x in e[0]:
    visited = set()
    mem = {x: 0 for x in range(1, n**2 + 1) if x %
           n == 0 or x % n == 1 or x <= n or x > n**2 - n}

    def solve(x):
        if x not in mem:
            visited.add(x)
            tmp = n**3
            for k in [x - 1, x + 1, x - n, x + n]:
                if k not in visited:
                    tmp = min(tmp, (k in viewers) + solve(k))
            visited.remove(x)
            mem[x] = tmp
        return mem[x]

    ans += solve(x)
    viewers.remove(x)

print(ans)

Submission status: Runtime Error

Solution code:
[n], *e = [[*map(int, t.split())] for t in open(0)]
viewers = set(range(1, n**2 + 1))
ans = 0

for x in e[0]:
    visited = set()

    def solve(x):
        if x % n == 0 or x % n == 1 or x <= n or x > n**2 - n:
            return 0
        else:
            visited.add(x)
            tmp = n**3
            for k in [x - 1, x + 1, x - n, x + n]:
                if k not in visited:
                    tmp = min(tmp, (k in viewers) + solve(k))
            visited.remove(x)
            return tmp

    ans += solve(x)
    viewers.remove(x)

print(ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
from numba import njit
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

@njit(cache=True)
def solve(N,M,P):
    d=[0]*M
    for i in range(N):
        for j in range(N):
            d[i*N+j]=min(min(i,N-1-i),min(j,N-1-j))
    used=[1]*M
    dx=(-1,1,-N,N)
    ans=0
    que=[]
    for p in P:
        ans+=d[p]
        used[p]=0
        que.append(p)
        while que:
            x=que.pop()
            for ddx in dx:
                nx=x+ddx
                if 0<=nx<M:
                    if used[x]==0 and d[nx]-d[x]>=1:
                        d[nx]-=1
                        que.append(nx)
                    elif used[x]==1 and d[nx]-d[x]>=2:
                        d[nx]-=1
                        que.append(nx)
    return ans

def main():
    N=int(input())
    M=N**2
    P=tuple(map(int1,input().split()))
    ans=solve(N,M,P)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
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] < l[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 sys
input = sys.stdin.readline
from collections import deque
n = int(input())
a = list(map(int,input().split()))
ls = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
  for j in range(n):
    ls[i][j] = min(i,j,n-1-i,n-1-j)
ans = 0
st = set()
for i in a:
  x,y = divmod(i-1,n)
  ans += ls[x][y]
  st.add((x,y))
  q = deque([i-1])
  while q:
    j = q.popleft()
    px,py = divmod(j,n)
    for nx,ny in (px-1,py),(px+1,py),(px,py+1),(px,py-1):
      if 0 <= nx < n and 0 <= ny < n:
        if (px,py) in st:
          if ls[px][py] < ls[nx][ny]:
            ls[nx][ny] = ls[px][py]
            q.append((nx,ny))
        elif ls[px][py]+1 < ls[nx][ny]:
          ls[nx][ny] = ls[px][py]+1
          q.append((nx,ny))
print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
a = list(map(int,input().split()))
ls = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
  for j in range(n):
    ls[i][j] = min(i,j,n-1-i,n-1-j)
ans = 0
st = set()
for i in a:
  x,y = divmod(i-1,n)
  ans += ls[x][y]
  set.add((x,y))
  q = deque([(x,y)])
  while q:
    px,py = q.popleft()
    for nx,ny in (px-1,py),(px+1,py),(px,py+1),(px,py-1):
      if 0 <= nx < n and 0 <= ny < n:
        if (nx,ny) in st:
          if ls[px][py] < ls[nx][ny]:
            ls[nx][ny] = ls[px][py]
        elif ls[px][py]+1 < ls[nx][ny]:
          ls[nx][ny] = ls[px][py]+1
          q.append((nx,ny))
print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!

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)

#print(dist)


#ans = [0]*N
ans = 0
iru = [1]*N

move = [-n,-1,1,n]
for pi in p:
    pi -= 1

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

    q = [pi]
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        for i in range(4):
            if i==2 and v%n==n-1: continue
            if i==1 and v%n==0: continue
            if i==0 and v < w: continue
            if i==3 and v+n >= N: continue
            nv = v+move[i]
            if dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        
                    
    #print(dist)        

print(ans)
if n==3: print(1)

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!

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)

#print(dist)


#ans = [0]*N
ans = 0
iru = [1]*N

move = [-n,-1,1,n]
for pi in p:
    pi -= 1

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

    q = [pi]
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        for i in range(4):
            if i==2 and v%n==n-1: continue
            if i==1 and v%n==0: continue
            if i==0 and v < w: continue
            if i==3 and v+w >= N: continue
            nv = v+move[i]
            if dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        
                    
    #print(dist)        

print(ans)
if n==3: print(1)

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!

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)

#print(dist)


#ans = [0]*N
ans = 0
iru = [1]*N

move = [-n,-1,1,n]
for pi in p:
    pi -= 1

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

    q = [pi]
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        for i in range(4):
            if i==2 and v%n==n-1: continue
            if i==1 and v%n==0: continue
            nv = v+a[i]
            if 0 <= nv < N and dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        
                    
    #print(dist)        

print(ans)
if n==3: print(1)

Submission status: Runtime Error

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

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

distance = [[min(i, j, n - i - 1, n - j - 1) for i in range(n)] for j in range(n)]
check = [[1] * n for i in range(n)]
p = [((i - 1) // n, (i - 1) % n) for i in p]
ans = 0
for i, j in p:
    ans += distance[j][i]
    d = deque((j ,i ,distance[j][i]))
    check[j][i] = 0
    while len(d):
        x, y, dis = d.popleft()
        for i in range(0, 4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

            if 0 <= nx < n and 0 <= ny < n:
                # 更新できるマスは更新
                if distance[nx][ny] > dis:
                    distance[nx][ny] = dis
                    d.append((nx, ny, dis + check[nx][ny]))

print(ans)

Submission status: Runtime Error

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

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

geta = N+2
G = [0]*(geta*geta)

for v in range(-1-(-N//2), -1, -1):
    l = v+1
    r = N-v
    for i in range(geta):
        G[i*geta+l] = v
        G[i*geta+r] = v
        G[l*geta+i] = v
        G[r*geta+i] = v

for i in range(geta):
    G[i*geta] = -1
    G[i*geta + geta-1] = -1
    G[i] = -1
    G[geta*(geta-1)+i] = -1

Pn = []

for p in P:
    a, b = divmod(p-1, N)
    Pn.append((1+a)*geta+1+b)

DIREC = [1, -1, geta, -geta]
ans = 0
used = [False]*(geta*geta)
for p in Pn:
    ans += G[p]
    res = G[p]
    for d in DIREC:
        res = min(res, G[p+d])
    if G[p] != res:
        G[p] = res
        
        while Q:
            vn = Q.pop()
            for d in DIREC:
                vf = vn + d
                if not used[vf]:
                    if G[vf] > G[vn] + 1:
                        G[vf] = G[vn] + 1
                        Q.appendleft(vf)
                else:
                    if G[vf] > G[vn]:
                        G[vf] = G[vn]
                        Q.appendleft(vf)
                    
    used[p] = True
print(ans)

Submission status: Runtime Error

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

thtr = [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 set_rnk2(pidx):
    tidx = ttidx(pidx)
    val = thtr[tidx]
    wk = min(thtr[tidx - 1],thtr[tidx + 1],thtr[tidx-(n+2)],thtr[tidx +n+2])
    #その場所が空席なら、周りの経路の最小値に合わせる。
    if psn[pidx] == 0 :
        if val != wk:
            thtr[tidx] = wk
        else:
            #自身を更新しないなら伝播不要
            return            
    else:
        if val > wk + 1:
            thtr[tidx] = wk + 1
        else:
            #自身を更新しないなら伝播不要
            return

    #伝播
    wk = ppidx(tidx - 1)
    if wk >= 0:
        set_rnk2(wk)
    wk = ppidx(tidx + 1)
    if wk >= 0:
        set_rnk2(wk)
    wk = ppidx(tidx -n - 2 )
    if wk >= 0:
        set_rnk2(wk)
    wk = ppidx(tidx +n + 2 )
    if wk >= 0:
        set_rnk2(wk)

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

#処理
ans = 0
for el in p:
    psn[el-1]=0
    wk =  (thtr[ttidx(el-1)] - 1 )
    ans += wk
    set_rnk2(el-1)

print(ans)