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 numba import njit
n=int(input())
A=list(map(int,input().split()))
@njit
def solve(n,A):
    remain=[[1]*n for i in range(n)]

    que1=[]
    que2=[]
    ans=0
    for a in A:
        x,y=(a-1)//n,(a-1)%n
        remain[x][y]=0
        que2.append((x,y))
        check=[[0]*n for i in range(n)]
        check[x][y]=1
        endflag=0
        for i in range(0,501):
            newque=[]
            while que1:
                x,y=que1.pop()
                for nx,ny in ((x-1,y),(x+1,y),(x,y+1),(x,y-1)):
                    if nx<0 or ny<0 or nx>=n or ny>=n:
                        endflag=1
                        break
                    if check[nx][ny]==0:
                        check[nx][ny]=1
                        if remain[nx][ny]:
                            newque.append((nx,ny))
                        else:
                            que2.append((nx,ny))
            while que2:
                x,y=que2.pop()
                for nx,ny in ((x-1,y),(x+1,y),(x,y+1),(x,y-1)):
                    if nx<0 or ny<0 or nx>=n or ny>=n:
                        endflag=1
                        break
                    if check[nx][ny]==0:
                        check[nx][ny]=1
                        if remain[nx][ny]:
                            newque.append((nx,ny))
                        else:
                            que2.append((nx,ny))
            if endflag:
                break
            que1=newque
        ans+=i
    print(ans)
solve(n,A)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

cost = [[0]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        cost[i][j]=min(min(i,n-i-1),min(j,n-j-1))
dx=[1,0,-1,0]
dy=[0,1,0,-1]
ans=0
reach=42
for i in range(n*n):
    pi = (p[i]-1)%n
    pj = (p[i]-1)//n
    cnt=cost[pi][pj]
    ans+=cost[pi][pj]
    cost[pi][pj]=-cnt-reach
    d=deque()
    d.append((pi,pj,cnt))
    while d:
        ni,nj,cnt=d.popleft()
        for j in range(4):
            nwi = ni+dx[j]
            nwj = nj+dy[j]
            if not(0<=nwi<n):
                continue
            if not(0<=nwj<n):
                continue
            if cost[nwi][nwj]>cnt:
                cost[nwi][nwj]=cnt
                d.append((nwi,nwj,cnt+1))
                continue
            if -cost[nwi][nwj]-reach>cnt:
                cost[nwi][nwj]=-cnt-reach
                d.append((nwi,nwj,cnt))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

cost = [[0]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        cost[i][j]=min(min(i,n-i-1),min(j,n-j-1))
dx=[1,0,-1,0]
dy=[0,1,0,-1]
ans=0
for i in range(n*n):
    pi = (p[i]-1)%n
    pj = (p[i]-1)//n
    cnt=cost[pi][pj]
    ans+=cost[pi][pj]
    cost[pi][pj]=-cnt
    d=deque()
    d.append((pi,pj,cnt))
    while d:
        ni,nj,cnt=d.popleft()
        for j in range(4):
            nwi = ni+dx[j]
            nwj = nj+dy[j]
            if not(0<=nwi<n):
                continue
            if not(0<=nwj<n):
                continue
            if cost[nwi][nwj]>cnt:
                cost[nwi][nwj]=cnt
                d.append((nwi,nwj,cnt+1))
                continue
            if -cost[nwi][nwj]>cnt:
                cost[nwi][nwj]=-cnt
                d.append((nwi,nwj,cnt))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

rev_p = [0] * (n * n)
for offset in range(len(p)):
    rev_p[p[offset] - 1] = offset

costs = [0] * (n * n)

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

removed = set()

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

    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 < n * n:
                next_cost = cost if pos in removed else cost + 1

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def main():
    n = int(input())
    p = list(map(int, input().split()))
    for i in range(len(p)):
        p[i] -= 1
    
    to_outsides = [[0]*n for _ in range(n)]
    not_exist = [[False]*n for _ in range(n)]
    
    for i in range(n):
        for j in range(n):
            to_outside = [i,n-1-i,j,n-1-j]
            to_outsides[i][j] = min(to_outside)
    
    directions = [[-1,0],[1,0],[0,-1],[0,1]]

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def main():
  n = int(input())
  p = list(map(int, input().split()))
  for i in range(len(p)):
      p[i] -= 1

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


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

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

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

      for renew in renews:
          if to_outsides[renew[0]][renew[1]] != 0:
              to_outsides[renew[0]][renew[1]]-=1
  print(answer)

main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def main():
  n = int(input())
  p = list(map(int, input().split()))
  for i in range(len(p)):
      p[i] -= 1

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


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

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

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

      for renew in renews:
          if to_outsides[renew[0]][renew[1]] != 0:
              to_outsides[renew[0]][renew[1]]-=1
  print(answer)

main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy

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

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


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

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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
p = list(map(int, input().split()))
for i in range(len(p)):
    p[i] -= 1

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


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

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


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

Submission status: Time Limit Exceeded

Solution code:
import sys
def main():
    input = sys.stdin.readline
    n = int(input())
    p = list(map(int,input().split()))
    p = [((i-1)//n,(i-1)%n) for i in p]
    g = [[min(i,j,n-i-1,n-j-1) for j in range(n)] for i in range(n)]
    a = [[True]*n for i in range(n)]
    ans = 0
    for y,x in p:
        ans += g[y][x]
        dq = [(y,x)]
        a[y][x] = 0
        while dq:
            y,x = dq.pop()
            m = g[y][x]
            u = a[y][x]
            if x != 0:
                if g[y][x-1] > m:
                    g[y][x-1] = m+u
                    dq.append((y,x-1))
            if x != n-1:
                if g[y][x+1] > m:
                    g[y][x+1] = m+u
                    dq.append((y,x+1))
            if y != 0:
                if g[y-1][x] > m:
                    g[y-1][x] = m+u
                    dq.append((y-1,x))
            if y != n-1:
                if g[y+1][x] > m:
                    g[y+1][x] = m+u
                    dq.append((y+1,x))
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from numba import njit

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

N = 1
A = [0]
M = 3
X = [-1, -1, -1, -1, 0, -1, -1, -1, -1]
Y = [0, 0, 0, 0, 1, 0, 0, 0, 0]
calc(N, M, A, X, Y)

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

Submission status: Time Limit Exceeded

Solution code:
from numba import njit

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

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

print(calc(N, M, A, X, Y))

Submission status: Time Limit Exceeded

Solution code:
from numba import njit

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]

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

Submission status: Time Limit Exceeded

Solution code:
# from numba import njit

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]

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

Submission status: Time Limit Exceeded

Solution code:
# from numba import njit
 
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]

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

print(calc(N, M, A, X, Y))

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
 
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]

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

print(calc(N, M, A, X, Y))

Submission status: Time Limit Exceeded

Solution code:
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
    S = {i0}
    dd = (-1, 1, M, -M)
    while Q:
        i, h = deque.popleft(Q)
        for d in dd:
            j = i + d
            if j in S: continue
            y = Y[j]
            if X[j] >= h + y:
                X[j] -= 1
                deque.append(Q, (j, h + y))
                S.add(j)
ans = 0
for a in A:
    aa = (a // N + 1) * M + a % N + 1
    ans += X[aa]
    calc(aa)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
  #n = int(input())
  #p = tuple(map(int,input().split()))
  import sys
  n,*p = map(int,sys.stdin.read().split())

  m = [0]*(n**2)
  #m = [[0 for _ in range(n)] for _ in range(n)]
  for i in range(n):
    for j in range(n):
      m[i*n+j] = min(i,n-1-i,j,n-1-j)
      #m[i][j] = min(i,n-1-i,j,n-1-j)
  #print(m)

  exist = [1]*(n**2)
  #exist = [[1 for _ in range(n)] for _ in range(n)]

  ans = 0
  for pi in p:
    #y,x = divmod(pi-1,n)
    ans += m[pi-1]
    #ans += m[y][x]
    exist[pi-1] = 0
    #exist[y][x] = 0
    q = [pi-1]
    #q = [(y,x)]
    while(len(q)>0):
      a = q.pop()
      qy,qx = divmod(a,n)
      #qy,qx = q.pop()
      for dy,dx in ((1,0),(-1,0),(0,1),(0,-1)):
        if qy+dy < 0 or qy+dy >= n or qx+dx < 0 or qx+dx >= n:
          continue
        if m[(qy+dy)*n+(qx+dx)] > m[qy*n+qx]+exist[qy*n+qx]:
          m[(qy+dy)*n+(qx+dx)] = m[qy*n+qx]+exist[qy*n+qx]
          q.append((qy+dy)*n+(qx+dx))
        #if m[qy+dy][qx+dx] > m[qy][qx]+exist[qy][qx]:
        #  m[qy+dy][qx+dx] = m[qy][qx]+exist[qy][qx]
        #  q.append((qy+dy,qx+dx))
  print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
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:
            if Q[ny, nx] > q:
                Q[ny, nx] = q
                dfs(N, Q, stay, ny * N + nx, q + stay[ny, nx])


@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 r in range(N//2+1):
        Q[r:N-r, r:N-r] = r

    ans = 0
    for p in P:
        y, x = divmod(p, N)
        stay[y, x] = 0
        q = Q[y, x]
        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))

Submission status: Time Limit Exceeded

Solution code:
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, y, x, q):
    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:
            if Q[ny, nx] > q:
                Q[ny, nx] = q
                dfs(N, Q, stay, ny, nx, q + stay[ny, nx])


@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 r in range(N//2+1):
        Q[r:N-r, r:N-r] = r

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


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

Submission status: Time Limit Exceeded

Solution code:
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, y, x, q):
    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:
            if Q[ny, nx] > q:
                Q[ny, nx] = q
                dfs(N, Q, stay, ny, nx, q + stay[ny, nx])


@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, j] = min([i, j, N-1-i, N-1-j])

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


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

Submission status: Time Limit Exceeded

Solution code:
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, y, x, q):
    s = stay[y, x]
    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:
            if Q[ny, nx] > q + s:
                Q[ny, nx] = q + s
                dfs(N, Q, stay, ny, nx, q + s)


@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.int32)
    
    for i in range(N):
        for j in range(N):
            Q[i, j] = min([i, j, N-1-i, N-1-j])

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


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

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
input = stdin.readline
import copy as cp
from collections import deque, OrderedDict

def VI(N, init=0):
  return [init for _ in range(N)]
def VVI(N, M, init=0):
  return [[init for _ in range(M)] for _ in range(N)]

def VD(N, init=0.0):
  return [init for _ in range(N)]
def VVD(N, M, init=0.0):
  return [[init for _ in range(M)] for _ in range(N)]

def Decimal(x):
  print("{0:.10f}".format(x))

class Pair:
  def __init__(self, x=0, y=0):
    self.first = x
    self.second = y

  def __repr__(self):
    return '{0} {1}'.format(self.first, self.second)

  def __lt__(self, pi):
    return self.first < pi.first

def POW(x, n):
  ret = 1
  while n:
    if n&1:
      ret *= x
    x *= x
    n >>= 1
  return ret

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

grid = VVI(N, N, True)
dist = VVI(N, N)
for i in range(N):
  for j in range(N):
    d = N-1
    d = min(d, i)
    d = min(d, j)
    d = min(d, N-1-i)
    d = min(d, N-1-j)
    dist[i][j] = d

dx = [0, 1, 0, -1] # u, r, d, l
dy = [-1, 0, 1, 0] # u, r, d, l

ans = 0
for p in P:
  p -= 1
  x = p % N
  y = p // N
  ans += dist[y][x]
  grid[y][x] = False
  q = deque([])
  q.append(p)
  while len(q) > 0:
    v = q.popleft()
    vx = v % N
    vy = v // N
    vp = grid[vy][vx]
    for i in range(4):
      ux = vx + dx[i]
      uy = vy + dy[i]
      if 0 <= ux and ux < N and 0 <= uy and uy < N:
        u = uy*N+ux
        nxtd = dist[vy][vx]
        if vp:
          nxtd+=1
        if dist[uy][ux] > nxtd:
          dist[uy][ux] = nxtd
          q.append(u)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
  #n = int(input())
  #p = tuple(map(int,input().split()))
  import sys
  n,*p = map(int,sys.stdin.read().split())

  m = [0]*(n**2)
  #m = [[0 for _ in range(n)] for _ in range(n)]
  for i in range(n):
    for j in range(n):
      m[i*n+j] = min(i,n-1-i,j,n-1-j)
      #m[i][j] = min(i,n-1-i,j,n-1-j)
  #print(m)

  exist = [1]*(n**2)
  #exist = [[1 for _ in range(n)] for _ in range(n)]

  ans = 0
  for pi in p:
    y,x = divmod(pi-1,n)
    a = y*n+x
    ans += m[a]
    #ans += m[y][x]
    exist[a] = 0
    #exist[y][x] = 0
    q = [a]
    #q = [(y,x)]
    while(len(q)>0):
      a = q.pop()
      qy,qx = divmod(a,n)
      #qy,qx = q.pop()
      for dy,dx in ((1,0),(-1,0),(0,1),(0,-1)):
        if qy+dy < 0 or qy+dy >= n or qx+dx < 0 or qx+dx >= n:
          continue
        if m[(qy+dy)*n+(qx+dx)] > m[qy*n+qx]+exist[qy*n+qx]:
          m[(qy+dy)*n+(qx+dx)] = m[qy*n+qx]+exist[qy*n+qx]
          q.append((qy+dy)*n+(qx+dx))
        #if m[qy+dy][qx+dx] > m[qy][qx]+exist[qy][qx]:
        #  m[qy+dy][qx+dx] = m[qy][qx]+exist[qy][qx]
        #  q.append((qy+dy,qx+dx))
  print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
def main():
  #n = int(input())
  #p = tuple(map(int,input().split()))
  import sys
  n,*p = map(int,sys.stdin.read().split())

  m = [0]*(n**2)
  #m = [[0 for _ in range(n)] for _ in range(n)]
  for i in range(n):
    for j in range(n):
      m[i*n+j] = min(i,n-1-i,j,n-1-j)
      #m[i][j] = min(i,n-1-i,j,n-1-j)
  #print(m)

  exist = [1]*(n**2)
  #exist = [[1 for _ in range(n)] for _ in range(n)]

  ans = 0
  for pi in p:
    y,x = divmod(pi-1,n)
    ans += m[y*n+x]
    #ans += m[y][x]
    exist[y*n+x] = 0
    #exist[y][x] = 0
    q = [(y,x)]
    while(len(q)>0):
      qy,qx = q.pop()
      for dy,dx in ((1,0),(-1,0),(0,1),(0,-1)):
        if qy+dy < 0 or qy+dy >= n or qx+dx < 0 or qx+dx >= n:
          continue
        if m[(qy+dy)*n+(qx+dx)] > m[qy*n+qx]+exist[qy*n+qx]:
          m[(qy+dy)*n+(qx+dx)] = m[qy*n+qx]+exist[qy*n+qx]
          q.append((qy+dy,qx+dx))
        #if m[qy+dy][qx+dx] > m[qy][qx]+exist[qy][qx]:
        #  m[qy+dy][qx+dx] = m[qy][qx]+exist[qy][qx]
        #  q.append((qy+dy,qx+dx))
  print(ans)

main()