Problem:


Score : 700 points

Problem Statement

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

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

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

Constraints

2 \le N \le 500

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

Input

The input is given from Standard Input in the format

N
P_1 P_2 \cdots P_{N^2}

Output

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

ans

Sample Input 1

3
1 3 7 9 5 4 8 6 2

Sample Output 1

1

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

1 2 3
4 5 6
7 8 9

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

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

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

Sample Input 2

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

Sample Output 2

3

Sample Input 3

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

Sample Output 3

11



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


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
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)]
exist = [1]*(n**2)


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


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


def generate_v2(v):
    i, j = to_idx(v)
    if 0 < i:
        yield v-n
    if i < n-1:
        yield v+n
    if 0 < j:
        yield v-1
    if j < n-1:
        yield v+1


def bfs(init_v):
    next_v = deque([init_v])
    exist[init_v] = 0
    while next_v:
        v = next_v.popleft()
        for v2 in generate_v2(v):
            if cost[v2] <= cost[v]+exist[v]:
                continue
            cost[v2] = cost[v]+exist[v]
            next_v.append(v2)


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

Submission status: Time Limit Exceeded

Solution code:
def main():
    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]

    def move(x, y, nx, ny):
        if distance[nx][ny] > distance[x][y] + check[x][y]:
            distance[nx][ny] = distance[x][y] + check[x][y]
            d.append((nx, ny))

    ans = 0
    for i, j in p:
        ans += distance[j][i]
        d = deque()
        d.append((j, i))
        check[j][i] = 0
        while len(d):
            x, y = d.popleft()
            if x != 0:
                move(x, y, x - 1, y)
            if x != n - 1:
                move(x, y, x + 1, y)
            if y != 0:
                move(x, y, x, y - 1)
            if y != n - 1:
                move(x, y, x, y + 1)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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]

def move(x,y,nx,ny):
    if distance[nx][ny] > distance[x][y] + check[x][y]:
        distance[nx][ny] = distance[x][y] + check[x][y]
        d.append((nx,ny))

ans = 0
for i, j in p:
    ans += distance[j][i]
    d=deque()
    d.append((j,i))
    check[j][i] = 0
    while len(d):
        x, y = d.popleft()
        if x!=0:
            move(x,y,x-1,y)
        if x!=n-1:
            move(x,y,x+1,y)
        if y!=0:
            move(x,y,x,y-1)
        if y!=n-1:
            move(x,y,x,y+1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
Ps = list(map(lambda x: int(x)-1, input().split()))
DIRC = [(-1, 0), (0, 1), (1, 0), (0, -1)]


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


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


cost = [0]*(n**2)
for v in range(n**2):
    i, j = to_idx(v)
    cost[v] = min(i, n-1-i, j, n-1-j)
exist = [1]*(n**2)


def bfs(init_v):
    next_v = deque([to_idx(init_v)])
    exist[init_v] = 0
    while next_v:
        i, j = next_v.popleft()
        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[to_v(i, j)]+exist[to_v(i, j)]
            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: Time Limit Exceeded

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
            v2 = to_v(x, y)
            if x < 0 or y < 0 or n <= x or n <= y:
                continue
            c = cost[v]+exist[v]
            if cost[v2] <= c:
                continue
            cost[v2] = c
            next_v.append(v2)


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

Submission status: Time Limit Exceeded

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

ans = 0
for p in Ps:
    ans += cost[p]
    next_v = deque([to_idx(p)])
    exist[p] = 0
    while next_v:
        i, j = next_v.popleft()
        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[to_v(i, j)]+exist[to_v(i, j)]
            if cost[to_v(x, y)] <= c:
                continue
            cost[to_v(x, y)] = c
            next_v.append((x, y))

print(ans)

Submission status: Time Limit Exceeded

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 bfs(init_v):
    next_v = deque([divmod(init_v, n)])
    exist[init_v] = 0
    while next_v:
        i, j = next_v.popleft()
        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[i*n+j]+exist[i*n+j]
            if cost[x*n+y] <= c:
                continue
            cost[x*n+y] = c
            next_v.append((x, y))


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

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    N = int(input())
    P = tuple(map(int, input().split()))

    Kcost = [0] * (N * N)
    for sn in range(N * N):
        row, clm = divmod(sn, N)
        Kcost[sn] = min(row, N - row - 1, clm, N - clm - 1)

    Sitting = [1] * (N * N)
    Kcount = 0

    for sn in P:
        csn = sn - 1
        Kcount += Kcost[csn]
        Sitting[csn] = 0
        queue = [csn]

        while queue:
            qsn = queue.pop()
            for dsn in (1, -1, N, -N):
                div, mod = divmod(qsn, N)
                if mod == 0 and dsn == -1: continue
                if mod == N - 1 and dsn == 1: continue
                if div == 0 and dsn == -N: continue
                if div == N - 1 and dsn == N: continue

                cdsn = qsn + dsn
                if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
                    Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
                    queue.append(cdsn)

    print(Kcount)


if __name__ == '__main__':
    main()

sys.exit()

Submission status: Time Limit Exceeded

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 bfs(init_v):
    def to_idx(p):
        i, j = divmod(p, n)
        return i, j

    def to_v(i, j):
        return i*n+j
    next_v = deque([to_idx(init_v)])
    exist[init_v] = 0
    while next_v:
        i, j = next_v.popleft()
        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[to_v(i, j)]+exist[to_v(i, j)]
            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: Time Limit Exceeded

Solution code:
import sys


def main():
    N = int(input())
    P = tuple(map(int, input().split()))

    Kcost = [min(row, N - 1 - row, clm, N - 1 - clm) for row in range(N) for clm in range(N)]

    Sitting = [1] * (N * N)
    Kcount = 0

    for sn in P:
        csn = sn - 1
        Kcount += Kcost[csn]
        Sitting[csn] = 0
        queue = [csn]

        while queue:
            qsn = queue.pop()
            for dsn in (1, -1, N, -N):
                div, mod = divmod(qsn, N)
                if mod == 0 and dsn == -1: continue
                if mod == N - 1 and dsn == 1: continue
                if div == 0 and dsn == -N: continue
                if div == N - 1 and dsn == N: continue

                cdsn = qsn + dsn
                if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
                    Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
                    queue.append(cdsn)

    print(Kcount)


if __name__ == '__main__':
    main()

sys.exit()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
Ps = list(map(lambda x: int(x)-1, input().split()))
cost = [min(min(i, n-1-i), min(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):
    i, j = divmod(p, n)
    return i, j


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


def bfs(init_v):
    next_v = deque([to_idx(init_v)])
    exist[init_v] = 0
    while next_v:
        i, j = next_v.popleft()
        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[to_v(i, j)]+exist[to_v(i, j)]
            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:
    if not cost[p]:
        bfs(p)
        continue
    ans += cost[p]
    bfs(p)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
input = sys.stdin.readline
n = int(input())
Ps = list(map(lambda x: int(x)-1, input().split()))
cost = [min(min(i, n-1-i), min(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):
    i, j = divmod(p, n)
    return i, j


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


def bfs(init_v):
    next_v = deque([to_idx(init_v)])
    exist[init_v] = 0
    while next_v:
        i, j = next_v.popleft()
        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[to_v(i, j)]+exist[to_v(i, j)]
            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: Time Limit Exceeded

Solution code:
import sys


def main():
    N = int(input())
    #P = tuple(map(int, input().split()))
    P = (map(int, input().split()))

    Kcost = [min(row, N - 1 - row, clm, N - 1 - clm) for row in range(N) for clm in range(N)]

    Sitting = [1] * (N * N)
    Kcount = 0


    #def Kcheck(qsn, cdsn):
    #    if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
    #        Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
    #        queue.append(cdsn)


    for sn in P:
        csn = sn - 1
        Kcount += Kcost[csn]
        Sitting[csn] = 0
        queue = [csn]

        while queue:
            qsn = queue.pop()
            div, mod = divmod(qsn, N)
            if mod: #Kcheck(qsn, qsn - 1)
                cdsn = qsn - 1
                if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
                    Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
                    queue.append(cdsn)
            if mod != N - 1: #Kcheck(qsn, qsn + 1)
                cdsn = qsn + 1
                if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
                    Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
                    queue.append(cdsn)
            if div: #Kcheck(qsn, qsn - N)
                cdsn = qsn - N
                if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
                    Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
                    queue.append(cdsn)
            if div != N - 1: #Kcheck(qsn, qsn + N)
                cdsn = qsn + N
                if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
                    Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
                    queue.append(cdsn)

    print(Kcount)


if __name__ == '__main__':
    main()

sys.exit()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
Ps = list(map(lambda x: int(x)-1, input().split()))
cost = [min(min(i, n-1-i), min(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):
    i, j = divmod(p, n)
    return i, j


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


def bfs(init_v):
    next_v = deque([to_idx(init_v)])
    exist[init_v] = 0
    while next_v:
        i, j = next_v.popleft()
        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[to_v(i, j)]+exist[to_v(i, j)]
            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: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
Ps = list(map(lambda x: int(x)-1, input().split()))
cost = [min(min(i, n-1-i), min(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):
    i, j = divmod(p, n)
    return i, j


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


def bfs(init_v):
    next_v = deque([to_idx(init_v)])
    exist[init_v] = 0
    while next_v:
        i, j = next_v.popleft()
        c = cost[to_v(i, j)]+exist[to_v(i, j)]
        for di, dj in DIRC:
            x, y = i+di, j+dj
            if x < 0 or y < 0 or n <= x or n <= y:
                continue
            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: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
Ps = list(map(lambda x: int(x)-1, input().split()))
cost = [min(min(i, n-1-i), min(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):
    i, j = divmod(p, n)
    return i, j


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


def bfs(init_v):
    next_v = deque([to_idx(init_v)])
    exist[init_v] = 0
    while next_v:
        i, j = next_v.popleft()

        for di, dj in DIRC:
            x, y = i+di, j+dj
            if x < 0 or y < 0 or n <= x or n <= y:
                continue

            if cost[to_v(x, y)] <= cost[to_v(i, j)]+exist[to_v(i, j)]:
                continue
            cost[to_v(x, y)] = cost[to_v(i, j)]+exist[to_v(i, j)]
            next_v.append((x, y))


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

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    N = int(input())
    #P = tuple(map(int, input().split()))
    P = (map(int, input().split()))

    Kcost = [min(row, N - 1 - row, clm, N - 1 - clm) for row in range(N) for clm in range(N)]

    Sitting = [1] * (N * N)
    Kcount = 0


    def Kcheck(qsn, cdsn):
        if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
            Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
            queue.append(cdsn)


    for sn in P:
        csn = sn - 1
        Kcount += Kcost[csn]
        Sitting[csn] = 0
        queue = [csn]

        while queue:
            qsn = queue.pop()
            div, mod = divmod(qsn, N)
            if mod: Kcheck(qsn, qsn - 1)
            if mod != N - 1: Kcheck(qsn, qsn + 1)
            if div: Kcheck(qsn, qsn - N)
            if div != N - 1: Kcheck(qsn, qsn + N)

    print(Kcount)


if __name__ == '__main__':
    main()

sys.exit()

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    N = int(input())
    P = tuple(map(int, input().split()))

    Kcost = [min(row, N - 1 - row, clm, N - 1 - clm) for row in range(N) for clm in range(N)]

    Sitting = [1] * (N * N)
    Kcount = 0


    def Kcheck(qsn, cdsn):
        if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
            Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
            queue.append(cdsn)


    for sn in P:
        csn = sn - 1
        Kcount += Kcost[csn]
        Sitting[csn] = 0
        queue = [csn]

        while queue:
            qsn = queue.pop()
            div, mod = divmod(qsn, N)
            if mod: Kcheck(qsn, qsn - 1)
            if mod != N - 1: Kcheck(qsn, qsn + 1)
            if div: Kcheck(qsn, qsn - N)
            if div != N - 1: Kcheck(qsn, qsn + N)

    print(Kcount)


if __name__ == '__main__':
    main()

sys.exit()

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    N = int(input())
    P = tuple(map(int, input().split()))

    Kcost = [0] * (N * N)
    for sn in range(N * N):
        row, clm = divmod(sn, N)
        Kcost[sn] = min(row, N - row - 1, clm, N - clm - 1)

    Sitting = [1] * (N * N)
    Kcount = 0


    def Kcheck(qsn, cdsn):
        if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
            Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
            queue.append(cdsn)


    for sn in P:
        csn = sn - 1
        Kcount += Kcost[csn]
        Sitting[csn] = 0
        queue = [csn]

        while queue:
            qsn = queue.pop()
            div, mod = divmod(qsn, N)
            if mod: Kcheck(qsn, qsn - 1)
            if mod != N - 1: Kcheck(qsn, qsn + 1)
            if div: Kcheck(qsn, qsn - N)
            if div != N - 1: Kcheck(qsn, qsn + N)

    print(Kcount)


if __name__ == '__main__':
    main()

sys.exit()

Submission status: Time Limit Exceeded

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


def bfs(init_v):
    next_v = deque([to_idx(init_v)])
    exist[init_v] = 0
    dist = [INF]*(n**2)
    dist[init_v] = cost[init_v]
    while next_v:
        i, j = next_v.popleft()

        for di, dj in DIRC:
            x, y = i+di, j+dj
            if x < 0 or y < 0 or n <= x or n <= y:
                continue

            if dist[to_v(x, y)] <= dist[to_v(i, j)]+exist[to_v(i, j)]:
                continue
            dist[to_v(x, y)] = dist[to_v(i, j)]+exist[to_v(i, j)]

            if cost[to_v(x, y)] <= dist[to_v(x, y)]:
                continue
            cost[to_v(x, y)] = dist[to_v(x, y)]
            next_v.append((x, y))


def to_idx(p):
    i, j = divmod(p, n)
    return i, j


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


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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import lru_cache


def main():
    N = int(input())
    P = tuple(map(int, input().split()))

    Kcost = [0] * (N * N)
    for sn in range(N * N):
        row, clm = divmod(sn, N)
        Kcost[sn] = min(row, N - row - 1, clm, N - clm - 1)

    Sitting = [1] * (N * N)
    Kcount = 0


    #@lru_cache(maxsize=None)
    def Kcheck(csn, qsn, cdsn):
        if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
            Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
            queue.append(cdsn)


    for sn in P:
        csn = sn - 1
        Kcount += Kcost[csn]
        Sitting[csn] = 0
        queue = [csn]

        while queue:
            qsn = queue.pop()
            for dsn in (1, -1, N, -N):
                div, mod = divmod(qsn, N)
                if mod == 0 and dsn == -1: continue
                if mod == N - 1 and dsn == 1: continue
                if div == 0 and dsn == -N: continue
                if div == N - 1 and dsn == N: continue

                Kcheck(csn, qsn, qsn + dsn)

    print(Kcount)


if __name__ == '__main__':
    main()

sys.exit()

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import lru_cache


def main():
    N = int(input())
    P = tuple(map(int, input().split()))

    Kcost = [0] * (N * N)
    for sn in range(N * N):
        row, clm = divmod(sn, N)
        Kcost[sn] = min(row, N - row - 1, clm, N - clm - 1)

    Sitting = [1] * (N * N)
    Kcount = 0


    @lru_cache(maxsize=None)
    def Kcheck(csn, qsn, cdsn):
        if Kcost[cdsn] > Kcost[qsn] + Sitting[qsn]:
            Kcost[cdsn] = Kcost[qsn] + Sitting[qsn]
            queue.append(cdsn)


    for sn in P:
        csn = sn - 1
        Kcount += Kcost[csn]
        Sitting[csn] = 0
        queue = [csn]

        while queue:
            qsn = queue.pop()
            for dsn in (1, -1, N, -N):
                div, mod = divmod(qsn, N)
                if mod == 0 and dsn == -1: continue
                if mod == N - 1 and dsn == 1: continue
                if div == 0 and dsn == -N: continue
                if div == N - 1 and dsn == N: continue

                Kcheck(csn, qsn, qsn + dsn)

    print(Kcount)


if __name__ == '__main__':
    main()

sys.exit()

Submission status: Time Limit Exceeded

Solution code:
def main():
    N, *P = map(int, open(0).read().split())

    dp = [0] + [min(i, j, N - 1 - i, N - 1 - j) for i in range(N) for j in range(N)]
    memo = [1] * (N * N + 1)

    def move(fr, to):
        if dp[to] > dp[fr] + memo[fr]:
            dp[to] = dp[fr] + memo[fr]
            S.append(to)

    ans = 0
    for p in P:
        ans += dp[p]
        memo[p] = 0

        S = [p]
        while S:
            v = S.pop()

            q, r = divmod(v - 1, N)
            if r != 0:
                move(v, v - 1)
            if r != N - 1:
                move(v, v + 1)
            if q < N - 1:
                move(v, v + N)
            if q >= 1:
                move(v, v - N)

    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
N, *P = map(int, open(0).read().split())

dp = [0] + [min(i, j, N - 1 - i, N - 1 - j) for i in range(N) for j in range(N)]
memo = [1] * (N * N + 1)

def move(fr, to):
    if dp[to] > dp[fr] + memo[fr]:
        dp[to] = dp[fr] + memo[fr]
        S.append(to)

ans = 0
for p in P:
    ans += dp[p]
    memo[p] = 0

    S = [p]
    while S:
        v = S.pop()

        q, r = divmod(v - 1, N)
        if r != 0:
            move(v, v - 1)
        if r != N - 1:
            move(v, v + 1)
        if q < N - 1:
            move(v, v + N)
        if q >= 1:
            move(v, v - N)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

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

DP=[[-1]*N for i in range(N)]
for i in range(N):
    for j in range(N):
        DP[i][j]=min(i,j,N-1-i,N-1-j)

USED=[[1]*N for i in range(N)]
ANS=0
    
for p in P:
    q,r=divmod(p-1,N)
    ANS+=DP[q][r]
    DP[q][r]-=1
    USED[q][r]=0

    Q=[(q,r)]

    while Q:
        x,y=Q.pop()

        for z,w in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
            if 0<=z<N and 0<=w<N:
                if DP[z][w]>DP[x][y]+USED[z][w]:
                    DP[z][w]=DP[x][y]+USED[z][w]
                    Q.append((z,w))

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

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

DP=[[-1]*N for i in range(N)]
for i in range(N):
    for j in range(N):
        DP[i][j]=min(i,j,N-1-i,N-1-j)

USED=[[0]*N for i in range(N)]

ANS=0
    
for p in P:
    q,r=divmod(p-1,N)
    ANS+=DP[q][r]
    DP[q][r]-=1
    USED[q][r]=1

    Q=[(q,r)]

    while Q:
        x,y=Q.pop()

        for z,w in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
            if 0<=z<N and 0<=w<N:
                if DP[z][w]>DP[x][y]+1-USED[z][w]:
                    DP[z][w]=DP[x][y]+1-USED[z][w]
                    Q.append((z,w))

print(ANS)

Submission status: Time Limit Exceeded

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[:])")
@numba.njit
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+1, (n_i, n_j)))

    print(ret)


if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
import numpy as np


def cc_export():
    @njit('(i4, i4, i4[:], i4[:], i4[:], i4)')
    def update(n, w, que, there, cost, pos):
        que[0] = pos
        i, l = 0, 1
        while i < l:
            pos = que[i]
            i += 1
            c = cost[pos]
            t = there[pos]
            k = c + t
            for df in list([-w, w, -1, 1]):
                pp = pos + df
                if cost[pp] > k:
                    cost[pp] = k
                    que[l] = pp
                    l += 1

    @njit('(i4, i4[:])')
    def main(n, p):
        w = n + 2
        que = np.zeros(4 * w * w, dtype=np.int32)
        there = np.ones(w * w, dtype=np.int32)
        # there = np.array([
        #     1 if 1 <= i and i <= n and 1 <= j and j <= n else 0
        #     for j in range(w) for i in range(w)
        # ],
        #                  dtype=np.int32)
        cost = np.array([
            -1 if i == 0 or i == n + 1 or j == 0 or j == n + 1 else min(
                i - 1, n - i, j - 1, n - j) for j in range(w) for i in range(w)
        ],
                        dtype=np.int32)

        ans = 0
        for pos in p:
            # v = list(map(lambda x: ' ' if x == 0 else '*', list(there)))
            # for i in range(w):
            #     print(' '.join(v[i * w:(i + 1) * w]))
            # print(cost.reshape((w, w)))
            # print("add", cost[pos], "for", divmod(pos, w))
            ans += cost[pos]
            there[pos] = 0
            update(n, w, que, there, cost, pos)
        return ans

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


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

    def transform(t):
        y, x = divmod(int(t) - 1, n)
        return (y + 1) * (n + 2) + (x + 1)

    from solution import update, main
    n = int(input())
    p = np.array(list(map(transform, input().split())), dtype=np.int32)
    print(main(n, p))