Problem:
 Score : 700 points    Problem Statement Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2 .  At the end of the movie, the viewers go out of the cinema in a certain order: the i -th viewer leaving her seat is the one denoted by the number P_i . The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat.
To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column).
While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y ; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.  Compute the number of pairs of viewers (x, y) such that y will hate x forever.      Constraints  2 \le N \le 500  The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \{1, 2, \dots, N^2\} .         Input The input is given from Standard Input in the format  N  P_1  P_2  \cdots  P_{N^2}       Output If ans is the number of pairs of viewers described in the statement, you should print on Standard Output  ans         Sample Input 1 3
1 3 7 9 5 4 8 6 2      Sample Output 1 1  Before the end of the movie, the viewers are arranged in the cinema as follows:  1 2 3
4 5 6
7 8 9  The first four viewers leaving the cinema ( 1 , 3 , 7 , 9 ) can leave the cinema without going through any seat, so they will not be hated by anybody.  Then, viewer 5 must go through one of the seats where viewers 2 , 4 , 6 , 8 are currently seated while leaving the cinema; hence he will be hated by at least one of those viewers.  Finally the remaining viewers can leave the cinema (in the order 4 , 8 , 6 , 2 ) without going through any occupied seat (actually, they can leave the cinema without going through any seat at all).       Sample Input 2 4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8      Sample Output 2 3       Sample Input 3 6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30      Sample Output 3 11

Solution (Python):
from collections import deque
n=int(input())
*p,=map(int, input().split())

for i in range(n*n):p[i]-=1
seats=[min(i//n,i%n,n-(i//n)-1,n-(i%n)-1) for i in range(n*n)] 

exist=[1]*(n*n)
dxy=(n,-n,1,-1)

ans=0
q=deque()
for pi in p:
    ans+=seats[pi]
    exist[pi]=0
    q.append(pi)
    while q:
        i=q.popleft()
        for dx in dxy:
            idx=i+dx
            if 0<=idx<n*n :
                if seats[i]+exist[i]<seats[idx]:
                    seats[idx]=seats[i]+exist[i]
                    q.append(idx)
print(ans)

Solution (Python):
n=int(input())
p=list(map(int,input().split()))
sheet=[min(i%n,i//n,n-i%n-1,n-i//n-1) for i in range(n**2)]
space=[1]*(n**2)
ans=0
for x in p:
  x-=1
  ans+=sheet[x]
  space[x]=0
  todo=[x]
  while todo:
    v=todo.pop()
    x,y=divmod(v,n)
    for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
      if 0<=x+dx<n and 0<=y+dy<n:
        nv=(x+dx)*n+(y+dy)
        if sheet[nv]>sheet[v]+space[v]:
          sheet[nv]=sheet[v]+space[v]
          todo.append(nv)
print(ans)

Solution (Python):
import sys
import numpy as np

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
    dh = (1, -1, 0, 0)
    dw = (0, 0, 1, -1)
    for p in P:
        h, w = divmod(p, N)
        ans += minDist[h][w]
        isFilled[h][w] = 0

        st = [(h, w)]
        while st:
            h, w = st.pop()
            dist = minDist[h][w] + isFilled[h][w]

            for i in range(4):
                toH, toW = h + dh[i], w + dw[i]
                if 0 <= toH < N and 0 <= toW < N:
                    if minDist[toH][toW] > dist:
                        minDist[toH][toW] = dist
                        st.append((toH, toW))
    return ans

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

if sys.argv[-1] == 'ONLINE_JUDGE':
    cc_export()
    exit(0)
if sys.argv[-1] != 'LOCAL':
    from my_module import main

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

print(main(N, P))

Solution (Python):
import sys
import numpy as np

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

        st = [(h, w)]
        while st:
            h, w = st.pop()
            dist = minDist[h][w] + isFilled[h][w]

            for toH, toW in ((h + 1, w), (h - 1, w), (h, w + 1), (h, w - 1)):
                if 0 <= toH < N and 0 <= toW < N:
                    if minDist[toH][toW] > dist:
                        minDist[toH][toW] = dist
                        st.append((toH, toW))
    return ans

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

if sys.argv[-1] == 'ONLINE_JUDGE':
    cc_export()
    exit(0)
if sys.argv[-1] != 'LOCAL':
    from my_module import main

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

print(main(N, P))

Solution (Python):
import sys
import numpy as np

if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC
    cc = CC('my_module')

    @cc.export('solve', 'i4(i4, i4[:])')
    def solve(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

            st = [(h, w)]
            while st:
                h, w = st.pop()
                dist = minDist[h][w] + isFilled[h][w]

                if h + 1 < N and minDist[h + 1][w] > dist:
                    minDist[h + 1][w] = dist
                    st.append((h + 1, w))
                if h - 1 >= 0 and minDist[h - 1][w] > dist:
                    minDist[h - 1][w] = dist
                    st.append((h - 1, w))
                if w + 1 < N and minDist[h][w + 1] > dist:
                    minDist[h][w + 1] = dist
                    st.append((h, w + 1))
                if w - 1 < N and minDist[h][w - 1] > dist:
                    minDist[h][w - 1] = dist
                    st.append((h, w - 1))
        return ans

    cc.compile()
    exit(0)

from my_module import solve

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

print(solve(N, P))

Solution (Python):
from collections import deque

n = int(input())
P = list(int(x) - 1 for x in input().split())
A = [0] * (n**2)
remain = [1] * (n**2)

for i in range(n**2):
    A[i] = min(i % n, n - (i % n) - 1, i // n, n - (i // n) - 1)

ans = 0
for i in range(n**2):
    ans += A[P[i]]
    remain[P[i]] = 0
    que = deque([P[i]])
    while que:
        k = que.popleft()
        if k % n != 0:  
            nk = k - 1
            if A[nk] > A[k] + remain[k]:
                A[nk] = A[k] + remain[k]
                que.append(nk)
        if n - (k % n) - 1 != 0:  
            nk = k + 1
            if A[nk] > A[k] + remain[k]:
                A[nk] = A[k] + remain[k]
                que.append(nk)
        if k // n != 0:  
            nk = k - n
            if A[nk] > A[k] + remain[k]:
                A[nk] = A[k] + remain[k]
                que.append(nk)
        if n - (k // n) - 1 != 0:  
            nk = k + n
            if A[nk] > A[k] + remain[k]:
                A[nk] = A[k] + remain[k]
                que.append(nk)

print(ans)

Solution (Python):
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N = NI()
    P = LI()

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

    r = [1] * (N*N)

    ans = 0
    q = []
    for p in P:
        p -= 1
        ans += s[p]
        r[p] = 0
        q.append(p)
        while q:
            a = q.pop()
            nc = s[a] + r[a]

            if a >= N:
                if s[a-N] > nc:
                    s[a-N] = nc
                    q.append(a-N)
            if a + N < N*N:
                if s[a+N] > nc:
                    s[a+N] = nc
                    q.append(a+N)
            if a % N:
                if s[a-1] > nc:
                    s[a-1] = nc
                    q.append(a-1)
            if a % N < N -1:
                if s[a+1] > nc:
                    s[a+1] = nc
                    q.append(a+1)

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N = NI()
    P = LI()

    s = []
    for i in range(N):
        for j in range(N):
            s.append(min(i,N-1-i,j,N-1-j))

    r = [1] * (N*N)

    ans = 0
    q = []
    for p in P:
        p -= 1
        ans += s[p]
        r[p] = 0
        q.append(p)
        while q:
            a = q.pop()
            nc = s[a] + r[a]

            if a >= N:
                if s[a-N] > nc:
                    s[a-N] = nc
                    q.append(a-N)
            if a + N < N*N:
                if s[a+N] > nc:
                    s[a+N] = nc
                    q.append(a+N)
            if a % N:
                if s[a-1] > nc:
                    s[a-1] = nc
                    q.append(a-1)
            if a % N < N -1:
                if s[a+1] > nc:
                    s[a+1] = nc
                    q.append(a+1)

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
from numba import njit
import numpy as np
@njit
def dfs(v,c,h,stay,todo):
    
    todo[0]=v
    now=0
    while now>=0:
        vv=todo[now]
        now-=1
        x,y=divmod(vv,n)
        for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
            nx,ny=x+dx,y+dy
            if 0<=nx<n and 0<=ny<n:
                nv=nx*n+ny
                if h[nv]>h[vv]+stay[vv]:
                    h[nv]=h[vv]+stay[vv]
                    now+=1
                    todo[now]=nv

@njit
def main(n,p):
    h=[min(i//n,n-i//n-1,i%n,n-i%n-1) for i in range(n**2)]
    h=np.array(h,np.int32)
    stay=np.full(n*n,1,np.int32)
    todo=np.zeros(n*n,np.int32)
    ans=0
    for v in p:
        c=h[v]
        ans+=c
        stay[v]=0
        dfs(v,c,h,stay,todo)
    print(ans)

if __name__=='__main__':
    n=int(input())
    p=np.array(list(map(int,input().split())),np.int32)
    p-=1
    main(n,p)

Solution (Python):
from numba import njit
import numpy as np
@njit
def dfs(v,c,h,stay):
    
    x,y=divmod(v,n)
    for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
        nx,ny=x+dx,y+dy
        if 0<=nx<n and 0<=ny<n:
            nv=nx*n+ny
            if h[nv]>c:
                h[nv]=c
                dfs(nv,c+stay[nv],h,stay)

@njit
def main(n,p):
    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

    for v in p:
        c=h[v]
        ans+=c
        stay[v]=0
        dfs(v,c,h,stay)
    print(ans)

    
    
if __name__=='__main__':
    n=int(input())
    p=np.array(list(map(int,input().split())),np.int32)
    p-=1
    main(n,p)

Solution (Python):
def examA():
    T = I()
    ans = [inf]*T
    for t in range(T):
        N, A, B, C, D = LI()
        num = [[2,A],[3,B],[5,C]]
        dp = defaultdict(lambda: inf)
        dp[N] = 0
        que = deque()
        que.append(N)
        while(que):
            now = que.pop()
            if now==0:
                continue
            cur = dp[now] + D*now
            if cur<dp[0]:
                dp[0] = cur
            cur = dp[now]
            for n,K in num:
                curn = cur + (now % n) * D + K
                if curn < dp[(now - now % n) // n]:
                    dp[(now - now % n) // n] = curn
                    que.append((now - now % n) // n)
                curn_ = cur + (-now % n) * D + K
                if curn_ < dp[(now + (-now % n)) // n]:
                    dp[(now + (-now % n)) // n] = curn_
                    que.append((now + (-now % n)) // n)
        ans[t] = dp[0]
    for v in ans:
        print(v)
    return

def examB():
    N = I()
    P = LI()
    L = [[min(i,j,N+1-i,N+1-j)for i in range(1,N+1)]for j in range(1,N+1)]
    exist = [[1]*N for _ in range(N)]
    cost = 0
    def bfs(s):
        que = deque()
        que.appendleft(s)

        def calc_L(h, w, h1, w1):
            c = L[h][w] + exist[h + h1][w + w1]
            if c < L[h + h1][w + w1]:
                L[h + h1][w + w1] = c
                s1 = (h + h1) * N + (w + w1) + 1
                
                que.appendleft(s1)
            return

        while(que):
            now = que.pop()
            h,w = (now-1)//N,(now-1)%N
            if 0<h:
                calc_L(h,w,-1,0)
            if h+1<N:
                calc_L(h,w,1,0)
            if 0<w:
                calc_L(h,w,0,-1)
            if w+1<N:
                calc_L(h,w,0,1)

        return

    
        
    
    for p in P:
        h,w = (p-1)//N,(p-1)%N
        exist[h][w] = 0
        if 0<L[h][w]:
            L[h][w] -= 1
        bfs(p)
        cost += L[h][w]
        
    
        
    ans = cost
    print(ans)
    return

def examB2():
    N = I()
    P = LI()
    L = [min(i,j,N+1-i,N+1-j) for i in range(1,N+1) for j in range(1,N+1)]
    exist = [1]*(N**2)
    cost = 0
    def bfs(s):
        que = deque()
        que.appendleft(s)

        def calc_L(s, s1):
            c = L[s] + exist[s1]
            if c < L[s1]:
                L[s1] = c
                que.appendleft(s1)
            return

        while(que):
            now = que.pop()
            if 0<now:
                calc_L(now,now-1)
            if now+1<N**2:
                calc_L(now,now+1)
            if 0<=now-N:
                calc_L(now,now-N)
            if now+N<N**2:
                calc_L(now,now+N)

        return

    for p in P:
        p -= 1
        exist[p] = 0
        if 0<L[p]:
            L[p] -= 1
        bfs(p)
        cost += L[p]
    ans = cost
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return


import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examB2()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Solution (Python):
n = int(input())
p = list(map(int, input().split()))
d = [min(i, n - i - 1, j, n - j - 1) for i in range(n) for j in range(n)]
ans = 0
l = [1] * (n ** 2)
for i in p:
    ans += d[i - 1]
    l[i - 1] = 0
    que = [i - 1]
    while que:
        s = que.pop()
        if not s % n == n - 1:
            if d[s + 1] > d[s] + l[s]:
                que.append(s + 1)
                d[s + 1] = d[s] + l[s]
        if s % n:
            if d[s - 1] > d[s] + l[s]:
                que.append(s - 1)
                d[s - 1] = d[s] + l[s]
        if s >= n:
            if d[s - n] > d[s] + l[s]:
                que.append(s - n)
                d[s - n] = d[s] + l[s]
        if n ** 2 > s + n:
            if d[s + n] > d[s] + l[s]:
                que.append(s + n)
                d[s + n] = d[s] + l[s]
print(ans)

Solution (Python):
from numba import njit
import numpy as np
@njit
def dfs(v,c,h,stay):
    
    x,y=divmod(v,n)
    for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
        nx,ny=x+dx,y+dy
        if 0<=nx<n and 0<=ny<n:
            nv=nx*n+ny
            if h[nv]>c:
                h[nv]=c
                dfs(nv,c+stay[nv],h,stay)

@njit
def main(n,p):
    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

    for v in p:
        c=h[v]
        ans+=c
        stay[v]=0
        dfs(v,c,h,stay)
    print(ans)

    
    
if __name__=='__main__':
    n=int(input())
    p=np.array(list(map(int,input().split())),np.int32)
    p-=1
    main(n,p)

Solution (Python):
def main(N,P):
    ad=(1,N,-1,-N)
    X=[0]*N*N
    for i in range(N*N):
        X[i]=min(i//N,N-1-i//N,i%N,N-1-i%N)
    E=[1]*N*N
    a=0
    q=[0]*N*N*N
    l,r=0,0
    for p in P:
        p-=1
        a+=X[p]
        E[p]=0
        q[r]=p
        r+=1
        while l<r:
            i=q[l]
            l+=1
            for j in ad:
                if 0<=i+j<N*N and X[i]+E[i]<X[i+j]:
                    X[i+j]=X[i]+E[i]
                    q[r]=i+j
                    r+=1
    return a
import sys
import numpy as np
readline=sys.stdin.buffer.readline
read=sys.stdin.buffer.read
if sys.argv[-1]=='ONLINE_JUDGE':
    from numba import*
    from numba.pycc import CC
    cc=CC('my_module')
    def cc_export(f,signature):
        cc.export(f.__name__,signature)(f)
        return njit(f)
    main=cc_export(main,(i8,i8[:],))
    cc.compile()
    exit()
N=int(readline())
P=np.array(readline().split(),dtype=np.int64)
from my_module import main
print(main(N,P))

Solution (Python):
from collections import deque

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] * (N ** 2)

ans = 0

def update(np, p):
    if MAP[np] > MAP[p] + d[p]:
        q.append(np)
        MAP[np] = MAP[p] + d[p]

for p in P:
    p -= 1
    
    d[p] = 0
    
    ans += MAP[p]
    
    q = deque()
    
    q.append(p)
    
    while len(q) != 0:
        p = q.popleft()
        if p % N != N-1:
            update(p+1, p)
        if p % N != 0:
            update(p-1, p)
        if p // N != N-1:
            update(p+N, p)
        if p // N != 0:
            update(p-N, p)

print(ans)

Solution (Python):
import math

import queue
from collections import deque,defaultdict
import heapq as hpq
import time
from sys import stdin,setrecursionlimit


ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())

    cos = [min(i//n,n-1-i//n,i%n,n-1-i%n) for i in range(n**2)]

    p = [int(i)-1 for i in ipt().split()]
    ans = 0
    q = []
    dr = [-1,-n,1,n]
    al = [False]*(n**2)

    for pi in p:
        ans += cos[pi]
        q.append((cos[pi],pi))
        al[pi] = True
        while q:
            qc,qi = q.pop()
            ad = qc if al[qi] else qc+1
            for d in dr:
                if 0 <= d+qi < n**2 and cos[d+qi] > ad:
                    q.append((ad,d+qi))
                    cos[d+qi] = ad
    print(ans)

    return

if __name__ == '__main__':
    main()

Solution (Python):
import math

import queue
from collections import deque,defaultdict
import heapq as hpq
import time
from sys import stdin,setrecursionlimit


ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())

    cos = [[min(i,j,n-1-i,n-1-j) for i in range(n)] for j in range(n)]

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

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n = I()
P = LI()
L = [[min(x, y, n - x - 1, n - y - 1) for x in range(n)] for y in range(n)]
flg = [[1] * n for _ in range(n)]
ans = 0
for i in P:
    xi = (i - 1) % n
    yi = (i - 1) // n
    ans += L[yi][xi]
    flg[yi][xi] = 0
    q = [((i - 1) // n,  (i - 1) % n)]
    while q:
        a, b = q.pop()
        val = L[a][b] + flg[a][b]
        if a >= 1 and L[a - 1][b] > val:
            L[a - 1][b] = val
            q += [(a - 1, b)]
        if b >= 1 and L[a][b - 1] > val:
            L[a][b - 1] = val
            q += [(a, b - 1)]
        if a < n - 1 and L[a + 1][b] > val:
            L[a + 1][b] = val
            q += [(a + 1, b)]
        if b < n - 1 and L[a][b + 1] > val:
            L[a][b + 1] = val
            q += [(a, b + 1)]

print(ans)

Solution (Python):
import sys
import numpy as np
from numba import njit

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit('(i4,i4[:])',cache=True)
def main(n,p):
    ans = 0
    w = n+2
    grid = np.ones((w,w),np.int32)
    dis = np.zeros((w,w),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
    grid = grid.ravel()
    dis = dis.ravel()
    stack = np.empty_like(grid)
    for pos in p:
        pos -= 1
        x = pos % n + 1
        y = pos // n + 1
        v = y*w+x
        ans += dis[v]
        grid[v] = 0
        k = min(dis[v-1],dis[v+1],dis[v+w],dis[v-w])
        cur = 0
        stack[0] = v
        while cur >= 0:
            v = stack[cur]
            cur -= 1
            for dx in (-1,1,w,-w):
                next_v = v + dx
                k = dis[v]+grid[v]
                if dis[next_v] > k:
                    dis[next_v] = k
                    cur += 1
                    stack[cur] = next_v
    return ans

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

Solution (Python):
from collections import deque

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

costs = [0] * n2

for i in range(n2):
    costs[i] = min(i // n, n - i // n - 1, i % n, n - i % n - 1)

remains = [1] * n2

ans = 0
for i, pi in enumerate(p):
    ans += costs[pi-1]
    remains[pi-1] = 0

    d = deque()
    d.append((pi-1, costs[pi-1]))

    while d:
        pos, cost = d.popleft()

        for offset in [-1, -n, 1, n]:
            if 0 <= pos + offset < n2:
                next_cost = cost + remains[pos]

                if costs[pos+offset] > next_cost:
                    costs[pos+offset] = next_cost
                    d.append((pos+offset, next_cost))

print(ans)

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

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

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

ans = 0
for i in range(len(P)):
    P[i] -= 1
    x, y = divmod(P[i], N)
    ans += dp[x][y]
    presence[x][y] = 0

    Q = [(x, y)]
    
    while Q:
        x, y = Q.pop()
        new_value = dp[x][y] + presence[x][y]
        if 1 <= x and dp[x - 1][y] > new_value:
            dp[x - 1][y] = new_value
            Q.append((x - 1, y))
        if x < N - 1 and dp[x + 1][y] > new_value:
            dp[x + 1][y] = new_value
            Q.append((x + 1, y))
        if 1 <= y and dp[x][y - 1] > new_value:
            dp[x][y - 1] = new_value
            Q.append((x, y - 1))
        if y < N - 1 and dp[x][y + 1] > new_value:
            dp[x][y + 1] = new_value
            Q.append((x, y + 1))

print(ans)

Solution (Python):
from collections import deque
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]

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 = deque([(aa, h)])
    X[aa] -= 1
    Y[aa] = 0
    dd = (-1, 1, M, -M)
    while Q:
        i, h = deque.popleft(Q)
        for d in dd:
            j = i + d
            y = Y[j]
            if X[j] >= h + y:
                X[j] -= 1
                deque.append(Q, (j, h + y))
print(ans)

Solution (Python):
from collections import deque
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]

def calc(i0):
    h = X[i0]
    if h < 0: return
    Q = deque([(i0, h)])
    X[i0] -= 1
    Y[i0] = 0
    dd = (-1, 1, M, -M)
    while Q:
        i, h = deque.popleft(Q)
        for d in dd:
            j = i + d
            y = Y[j]
            if X[j] >= h + y:
                X[j] -= 1
                deque.append(Q, (j, h + y))
ans = 0
for a in A:
    aa = (a // N + 1) * M + a % N + 1
    ans += X[aa]
    calc(aa)
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
from numba import njit
import numpy


def read():
    N = int(input().strip())
    line = input().strip()
    P = numpy.fromstring(line, dtype=numpy.int32, sep=" ")
    return N, P


@njit
def dfs(N, Q, stay, p, q):
    y, x = divmod(p, N)
    for dy, dx in ((0, 1), (1, 0), (-1, 0), (0, -1)):
        ny, nx = y + dy, x + dx
        if 0 <= ny < N and 0 <= nx < N:
            np = ny * N + nx
            if Q[np] > q:
                Q[np] = q
                dfs(N, Q, stay, np, q + stay[np])


@njit
def np_solve(N, P, INF=10**9):
    P -= 1
    Q = numpy.empty(N*N, dtype=numpy.int32)
    stay = numpy.ones(N*N, dtype=numpy.bool_)
    
    for i in range(N):
        for j in range(N):
            Q[i*N+j] = min([i, j, N-i-1, N-j-1])

    ans = 0
    for p in P:
        stay[p] = 0
        q = Q[p]
        ans += q
        dfs(N, Q, stay, p, q)
    return ans


if __name__ == '__main__':
    outputs = np_solve(*read())
    if outputs is not None:
        print("{}".format(outputs))

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

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

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

ans = 0
for i in range(len(P)):
    P[i] -= 1
    x, y = divmod(P[i], N)
    ans += dp[x][y]
    presence[x][y] = 0

    Q = [(x, y)]
    while Q:
        x, y = Q.pop()
        new_value = dp[x][y] + presence[x][y]
        if 1 <= x and dp[x - 1][y] > new_value:
            dp[x - 1][y] = new_value
            Q.append((x - 1, y))
        if x < N - 1 and dp[x + 1][y] > new_value:
            dp[x + 1][y] = new_value
            Q.append((x + 1, y))
        if 1 <= y and dp[x][y - 1] > new_value:
            dp[x][y - 1] = new_value
            Q.append((x, y - 1))
        if y < N - 1 and dp[x][y + 1] > new_value:
            dp[x][y + 1] = new_value
            Q.append((x, y + 1))


print(ans)

Solution (Python):
def N(): return int(input())
def NM():return map(int,input().split())
def L():return list(NM())
def LN(n):return [N() for i in range(n)]
def LL(n):return [L() for i in range(n)]
import sys
sys.setrecursionlimit(10**6)
n=N()
p=L()
size=(n+1)**2+1
ans=[0]*size
for i in range(1,n+1):
    for j in range(1,n+1):
        k=i*(n+1)+j
        ans[k]=min(i-1,j-1,n-i,n-j)
c=[1]*size
di=[-1,1,n+1,-n-1]
def f(k,i):
    if k+i>=size:
        return
    if ans[k]+c[k]<ans[k+i]:
        ans[k+i]-=1
        q.append(k+i)
t=0
for i in p:
    y=i%n
    if y==0:
        y=n
    x=(i+n-1)//n
    k=x*(n+1)+y
    c[k]=0
    t+=ans[k]
    q=[k]
    while q:
        k=q.pop()
        f(k,1)
        f(k,-1)
        f(k,n+1)
        f(k,-n-1)
print(t)

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

Solution (Python):
import sys

N = int(input())
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)

sys.exit()