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

def Next(): return input()
def NextInt(): return int(Next())
def NextInts(): return map(int,input().split())
def Nexts(): return map(str,input().split())
def NextIntList(): return list(map(int,input().split()))
def RowInts(n): return [input() for i in range(n)]

def main():
    n = NextInt()
    da = NextIntList()
    for i in range(n*n):
        da[i] -= 1
    co = [[min(abs(i), abs(j), abs(n-i-1), abs(n-j-1)) for i in range(n)] for j in range(n)]
    ju = [[1 for i in range(n)] for j in range(n)]
    q = deque()
    ans = 0
    for i in range(n*n):
        nx, ny = da[i]//n, da[i]%n
        ans += co[nx][ny]
        ju[nx][ny] = 0
        q.append([nx, ny])
        while len(q) != 0:
            now = q.popleft()
            x, y = now[0],now[1]
            if x > 0 and co[x][y] + ju[x][y] < co[x-1][y]:
                co[x-1][y] = co[x][y] + ju[x][y]
                q.append([x-1, y])
            if x < n-1 and co[x][y] + ju[x][y] < co[x+1][y]:
                co[x+1][y] = co[x][y] + ju[x][y]
                q.append([x+1, y])
            if y > 0 and co[x][y] + ju[x][y] < co[x][y-1]:
                co[x][y-1] = co[x][y] + ju[x][y]
                q.append([x, y-1])
            if y < n-1 and co[x][y] + ju[x][y] < co[x][y+1]:
                co[x][y+1] = co[x][y] + ju[x][y]
                q.append([x, y+1])
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

from collections import deque

N = int(input())

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

Rab = []
for _ in range(0,N):
    Rab.append([1]*N)

CheckRab = []
for _ in range(0,N):
    CheckRab.append([0]*N)

cnt = 0

for Pi in P:

    # Piの客が訪れた場所をマークするための配列
    # X = まだ   O = 一度訪れた
    visit = []
    for _ in range(0,N):
        visit.append(list("X"*N))
    visit[(Pi-1)//N][(Pi-1)%N] = "O"

    # その場所を通る場合において，嫌われる客の最小数
    HateNum = [] 
    for _ in range(0,N):
        HateNum.append([0]*N)

    # Pi の客のスタート
    d = deque([[(Pi-1)//N, (Pi-1)%N]])
    
    while d:

        now = d.popleft()

        # 場外に出れるならOK
        if now[0]-1 == 0:
            if Rab[now[0]-1][now[1]] == 0:
                Rab[(Pi-1)//N][(Pi-1)%N] = 0
                break
        if now[0]+1 == N-1:
            if Rab[now[0]+1][now[1]] == 0:
                Rab[(Pi-1)//N][(Pi-1)%N] = 0
                break
        if now[1]-1 == 0:
            if Rab[now[0]][now[1]-1] == 0:
                Rab[(Pi-1)//N][(Pi-1)%N] = 0
                break
        if now[1]+1 == N-1:
            if Rab[now[0]][now[1]+1] == 0:
                Rab[(Pi-1)//N][(Pi-1)%N] = 0
                break

        # 場外に出れるならOK
        if now[0]-1 == -1:
            Rab[(Pi-1)//N][(Pi-1)%N] = 0
            break
        if now[0]+1 == N:
            Rab[(Pi-1)//N][(Pi-1)%N] = 0
            break
        if now[1]-1 == -1:
            Rab[(Pi-1)//N][(Pi-1)%N] = 0
            break
        if now[1]+1 == N:
            Rab[(Pi-1)//N][(Pi-1)%N] = 0
            break
        

        # now マスの左のマスが行ってない場合
        if visit[now[0]-1][now[1]] == "X":
            # もしその場所が誰か座ってル場合
            if Rab[now[0]-1][now[1]] == 1:
                visit[now[0]-1][now[1]] = "O" # その場所を行ったことにして
                HateNum[now[0]-1][now[1]] = HateNum[now[0]][now[1]]+1 # その場所のHateNumを今の場所のひとつ上に
                d.append([now[0]-1,now[1]]) # その場所を次のHateNumの順番で検するように右に追加する
            # もしその場所が誰も座っていない場合
            else:
                visit[now[0]-1][now[1]] = "O" # その場所を行ったことにして
                HateNum[now[0]-1][now[1]] = HateNum[now[0]][now[1]] # その場所のHateNumを今の場所と同じにして
                d.appendleft([now[0]-1,now[1]]) # その場所をすぐに調べるように左に追加する．

        # now マスの右のマスが行ってない場合
        if visit[now[0]+1][now[1]] == "X":
            # もしその場所が誰か座ってル場合
            if Rab[now[0]+1][now[1]] == 1:
                visit[now[0]+1][now[1]] = "O" # その場所を行ったことにして
                HateNum[now[0]+1][now[1]] = HateNum[now[0]][now[1]]+1 # その場所のHateNumを今の場所のひとつ上に
                d.append([now[0]+1,now[1]]) # その場所を次のHateNumの順番で検するように右に追加する
            # もしその場所が誰も座っていない場合
            else:
                visit[now[0]+1][now[1]] = "O" # その場所を行ったことにして
                HateNum[now[0]+1][now[1]] = HateNum[now[0]][now[1]] # その場所のHateNumを今の場所と同じにして
                d.appendleft([now[0]+1,now[1]]) # その場所をすぐに調べるように左に追加する．

        # now マスの上のマスが行ってない場合
        if visit[now[0]][now[1]-1] == "X":
            # もしその場所が誰か座ってル場合
            if Rab[now[0]][now[1]-1] == 1:
                visit[now[0]][now[1]-1] = "O" # その場所を行ったことにして
                HateNum[now[0]][now[1]-1] = HateNum[now[0]][now[1]]+1 # その場所のHateNumを今の場所のひとつ上に
                d.append([now[0],now[1]-1]) # その場所を次のHateNumの順番で検するように右に追加する
            # もしその場所が誰も座っていない場合
            else:
                visit[now[0]][now[1]-1] = "O" # その場所を行ったことにして
                HateNum[now[0]][now[1]-1] = HateNum[now[0]][now[1]] # その場所のHateNumを今の場所と同じにして
                d.appendleft([now[0],now[1]-1]) # その場所をすぐに調べるように左に追加する．

        # now マスの下のマスが行ってない場合
        if visit[now[0]][now[1]+1] == "X":
            # もしその場所が誰か座ってル場合
            if Rab[now[0]][now[1]+1] == 1:
                visit[now[0]][now[1]+1] = "O" # その場所を行ったことにして
                HateNum[now[0]][now[1]+1] = HateNum[now[0]][now[1]]+1 # その場所のHateNumを今の場所のひとつ上に
                d.append([now[0],now[1]+1]) # その場所を次のHateNumの順番で検するように右に追加する
            # もしその場所が誰も座っていない場合
            else:
                visit[now[0]][now[1]+1] = "O" # その場所を行ったことにして
                HateNum[now[0]][now[1]+1] = HateNum[now[0]][now[1]] # その場所のHateNumを今の場所と同じにして
                d.appendleft([now[0],now[1]+1]) # その場所をすぐに調べるように左に追加する．

    cnt += HateNum[now[0]][now[1]]

print(cnt)

Submission status: Time Limit Exceeded

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


diff = ((0, 1), (0, -1), (1, 0), (-1, 0))
n = int(input())
p = list(map(int, input().split()))

cost = [0] * (n * n)
for i in range(n):
    for j in range(n):
        cost[i * n + j] = min(i, j, n - i - 1, n - j - 1)

occ = [True] * (n * n)
ans = 0
for start in p:
    start -= 1
    q = deque([start])
    ans += cost[start]
    occ[start] = False
    while q:
        ij = q.popleft()
        i, j = divmod(ij, n)
        for di, dj in diff:
            nxt_ij = (i + di) * n + (j + dj)
            if not(0 <= i + di < n and 0 <= j + dj < n):
                continue
            if not occ[ij] and cost[nxt_ij] > cost[ij]:
                    cost[nxt_ij] = cost[ij]
                    q.append(nxt_ij)
            elif cost[nxt_ij] > cost[ij] + 1:
                    cost[nxt_ij] = cost[ij] + 1
                    q.append(nxt_ij)

print(ans)

Submission status: Time Limit Exceeded

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


diff = ((0, 1), (0, -1), (1, 0), (-1, 0))
n = int(input())
p = list(map(int, input().split()))

cost = [0] * (n * n)
for i in range(n):
    for j in range(n):
        cost[i * n + j] = min(i, j, n - i - 1, n - j - 1)

occ = [True] * (n * n)
ans = 0
for start in p:
    start -= 1
    q = deque([start])
    ans += cost[start]
    occ[start] = False
    while q:
        ij = q.popleft()
        i, j = divmod(ij, n)
        for di, dj in diff:
            nxt_i = i + di
            nxt_j = j + dj
            nxt_ij = nxt_i * n + nxt_j
            if not(0 <= nxt_i < n and 0 <= nxt_j < n):
                continue
            if not occ[ij]:
                if cost[nxt_ij] > cost[ij]:
                    cost[nxt_ij] = cost[ij]
                    q.append(nxt_ij)
            else:
                if cost[nxt_ij] > cost[ij] + 1:
                    cost[nxt_ij] = cost[ij] + 1
                    q.append(nxt_ij)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys,queue,math,copy,itertools,bisect,collections
from heapq import *

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**3
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    P = LI()

    seat = [[1] * N for _ in range(N)]
    zero = [[1] * N for _ in range(N)]

    ans = 0

    for i in P:
        x = (i-1) % N
        y = (i-1) // N

        dp = [[INF] * N for _ in range(N)]
        d = 0
        q = []
        heapify(q)
        heappush(q,(d,x,y))
        dp[x][y] = 0
        min_cnt = INF
        while q:
            d,i,j = heappop(q)
            for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                if not(0 <= i+di < N and 0 <= j+dj < N):
                    break
                if zero[i+di][j+dj] == 0:
                    break
                e = seat[i+di][j+dj]
                if dp[i+di][j+dj] > d+e:
                    dp[i+di][j+dj] = d+e
                    heappush(q,(d+e,i+di,j+dj))
            else:
                continue
            min_cnt = d
            break

        seat[x][y] = 0
        if min_cnt == 0:
            # q = collections.deque()
            # q.append((x,y))
            zero[x][y] = 0
            # while q:
            #     i,j = q.popleft()
            #     for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
            #         if not(0 <= i+di < N and 0 <= j+dj < N): continue
            #         if seat[i+di][j+dj] == 1 or zero[i+di][j+dj] == 0: continue
            #         zero[i+di][j+dj] = 0
            #         q.append((i+di,j+dj))
        ans += min_cnt
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys,queue,math,copy,itertools,bisect,collections
from heapq import *

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**3
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    P = LI()

    seat = [[1] * N for _ in range(N)]
    zero = [[1] * N for _ in range(N)]

    ans = 0

    for i in P:
        x = (i-1) % N
        y = (i-1) // N

        dp = [[INF] * N for _ in range(N)]
        d = 0
        q = []
        heapify(q)
        heappush(q,(d,x,y))
        dp[x][y] = 0
        min_cnt = INF
        while q:
            d,i,j = heappop(q)
            for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                if not(0 <= i+di < N and 0 <= j+dj < N):
                    break
                if zero[i+di][j+dj] == 0:
                    break
                e = seat[i+di][j+dj]
                if dp[i+di][j+dj] > d+e:
                    dp[i+di][j+dj] = d+e
                    heappush(q,(d+e,i+di,j+dj))
            else:
                continue
            min_cnt = d
            break

        seat[x][y] = 0
        if min_cnt == 0:
            q = collections.deque()
            q.append((x,y))
            zero[x][y] = 0
            while q:
                i,j = q.popleft()
                for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                    if not(0 <= i+di < N and 0 <= j+dj < N): continue
                    if seat[i+di][j+dj] == 1 or zero[i+di][j+dj] == 0: continue
                    zero[i+di][j+dj] = 0
                    q.append((i+di,j+dj))
        ans += min_cnt
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**3
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    P = LI()

    seat = [[1] * N for _ in range(N)]
    zero = [[1] * N for _ in range(N)]

    ans = 0

    for i in P:
        x = (i-1) % N
        y = (i-1) // N

        dp = [[INF] * N for _ in range(N)]
        d = 0
        q = collections.deque()
        q.append((x,y,d))
        dp[x][y] = 0
        min_cnt = INF
        while q:
            i,j,d = q.popleft()
            if d >= min_cnt: continue
            for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                if not(0 <= i+di < N and 0 <= j+dj < N):
                    break
                if zero[i+di][j+dj] == 0:
                    break
                e = seat[i+di][j+dj]
                if dp[i+di][j+dj] > d+e:
                    dp[i+di][j+dj] = d+e
                    q.append((i+di,j+dj,d+e))
            else:
                continue
            min_cnt = min(min_cnt,d)

        seat[x][y] = 0
        if min_cnt == 0:
            q = collections.deque()
            q.append((x,y))
            zero[x][y] = 0
            while q:
                i,j = q.popleft()
                for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                    if not(0 <= i+di < N and 0 <= j+dj < N): continue
                    if seat[i+di][j+dj] == 1 or zero[i+di][j+dj] == 0: continue
                    zero[i+di][j+dj] = 0
                    q.append((i+di,j+dj))
        ans += min_cnt
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**3
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    P = LI()

    seat = [[1] * N for _ in range(N)]
    zero = [[1] * N for _ in range(N)]

    ans = 0

    for i in P:
        x = (i-1) % N
        y = (i-1) // N

        dp = [[INF] * N for _ in range(N)]
        d = 0
        q = collections.deque()
        q.append((x,y,d))
        dp[x][y] = 0
        min_cnt = INF
        while q:
            i,j,d = q.popleft()
            for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                if not(0 <= i+di < N and 0 <= j+dj < N):
                    break
                if zero[i+di][j+dj] == 0:
                    break
                e = seat[i+di][j+dj]
                if dp[i+di][j+dj] > d+e:
                    dp[i+di][j+dj] = d+e
                    q.append((i+di,j+dj,d+e))
            else:
                continue
            min_cnt = min(min_cnt,d)

        seat[x][y] = 0
        if min_cnt == 0:
            q = collections.deque()
            q.append((x,y))
            zero[x][y] = 0
            while q:
                i,j = q.popleft()
                for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                    if not(0 <= i+di < N and 0 <= j+dj < N): continue
                    if seat[i+di][j+dj] == 1 or zero[i+di][j+dj] == 0: continue
                    zero[i+di][j+dj] = 0
                    q.append((i+di,j+dj))
        ans += min_cnt
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

def solve():
      input = sys.stdin.readline
      N = int(input())
      P = [int(p) - 1 for p in input().split()]
      fin = [[1 for j in range(N)] for i in range(N)]
      d = [[min(min(i, N-i-1), min(j, N-j-1)) for j in range(N)] for i in range(N)]      
      move = ((-1, 0), (0, -1), (1, 0), (0, 1))
  
      count = 0
      q = deque()
      for i, p in enumerate(P):
            x, y = p // N, p % N
            count += d[x][y]
            fin[x][y] = 0
            for dx, dy in move:
                  if 0<=x+dx<N and 0<=y+dy<N and d[x][y] < d[x+dx][y+dy]:
                        d[x+dx][y+dy] = d[x][y]
                        q.append((x+dx, y+dy))
            while q:
                  nx, ny = q.popleft()
                  for dx, dy in move:
                        if 0<=nx+dx<N and 0<=ny+dy<N and d[nx][ny] + fin[nx][ny] < d[nx+dx][ny+dy]:
                              d[nx+dx][ny+dy] = d[nx][ny] + fin[nx][ny]
                              q.append((nx+dx, ny+dy))

      print(count)
            
      return 0

if __name__ == "__main__":
      solve()

Submission status: Time Limit Exceeded

Solution code:

import queue
import sys
input = sys.stdin.buffer.readline


def main():
    N = int(input())
    aa = list(map(int, input().split()))

    mm = [[0] * N for _ in range(N)]

    for i in range((N + 1) // 2):
        j = N - i - 1

        for x in range(i, j + 1):
            mm[i][x] = i
            mm[j][x] = i
            mm[x][i] = i
            mm[x][j] = i

    is_none = [[False] * N for _ in range(N)]

    ans = 0

    for a in aa:
        x = (a - 1) % N
        y = (a - 1) // N

        ans += mm[y][x]

        is_none[y][x] = True

        mm[y][x] -= 1

        q = queue.Queue()
        q.put((x, y, mm[y][x]))
        while not q.empty():
            x0, y0, n = q.get()

            xx = [x0, x0, x0 + 1, x0 - 1]
            yy = [y0 + 1, y0 - 1, y0, y0]
            for x, y in zip(xx, yy):
                if x < 0 or N <= x or y < 0 or N <= y:
                    continue

                if is_none[y][x]:
                    if mm[y][x] > n:
                        mm[y][x] = n
                        q.put((x, y, mm[y][x]))
                else:
                    if mm[y][x] > n + 1:
                        mm[y][x] = n + 1
                        q.put((x, y, mm[y][x]))

    return ans


if __name__ == "__main__":
    ans = main()
    print(ans)

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

def nears(n):
    ret = []
    if n%N != 0:
        ret.append(n-1)
    if n%N != N-1:
        ret.append(n+1)
    if n//N != 0:
        ret.append(n-N)
    if n//N != N-1:
        ret.append(n+N)
    return ret

NeedS = []
for p in range(N**2):
    NeedS.append(min([p%N, p//N, N-1-p%N, N-1-p//N]))

isChecked = [False]*(N**2)
ans = 0
for p in P:
    p -= 1
    ans += NeedS[p]
    isChecked[p] = True
    q = [p]
    # q.append(p)
    while q:
        qq = []
        for p in q:
            d = NeedS[p]
            if not isChecked[p]: d += 1
            for np in nears(p):
                if d < NeedS[np]:
                    NeedS[np] = d
                    qq.append(np)
        q = qq
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
N = int(input())
aa = list(map(int, input().split()))


mm = [[0] * N for _ in range(N)]


for i in range((N + 1) // 2):
    j = N - i - 1

    for x in range(i, j + 1):
        mm[i][x] = i
        mm[j][x] = i
        mm[x][i] = i
        mm[x][j] = i


def pm():
    for m in mm:
        print(m)


is_none = [[False] * N for _ in range(N)]

ans = 0

for a in aa:
    x = (a - 1) % N
    y = (a - 1) // N

    # print(x, y)

    ans += mm[y][x]

    is_none[y][x] = True

    mm[y][x] -= 1

    q = queue.Queue()
    q.put((x, y, mm[y][x]))
    while not q.empty():
        x0, y0, n = q.get()

        xx = [x0, x0, x0 + 1, x0 - 1]
        yy = [y0 + 1, y0 - 1, y0, y0]
        for x, y in zip(xx, yy):
            if x < 0 or N <= x or y < 0 or N <= y:
                continue

            if is_none[y][x]:
                if mm[y][x] > n:
                    mm[y][x] = n
                    q.put((x, y, mm[y][x]))
            else:
                if mm[y][x] > n + 1:
                    mm[y][x] = n + 1
                    q.put((x, y, mm[y][x]))

    # pm()


print(ans)

Submission status: Time Limit Exceeded

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

N = int(input())
P = list(map(lambda x: int(x)-1, input().split()))

def nears(n):
    ret = []
    if n%N != 0:
        ret.append(n-1)
    if n%N != N-1:
        ret.append(n+1)
    if n//N != 0:
        ret.append(n-N)
    if n//N != N-1:
        ret.append(n+N)
    return ret

NeedS = []
for p in range(N**2):
    NeedS.append(min([p%N, p//N, N-1-p%N, N-1-p//N]))

isChecked = [False]*(N**2)
ans = 0
for p in P:
    ans += NeedS[p]
    isChecked[p] = True
    q = deque()
    q.append(p)
    while q:
        p = q.popleft()
        d = NeedS[p]
        if not isChecked[p]: d += 1
        for np in nears(p):
            if d < NeedS[np]:
                NeedS[np] = d
                q.append(np)
print(ans)

Submission status: Time Limit Exceeded

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


diff = ((0, 1), (0, -1), (1, 0), (-1, 0))
n = int(input())
p = list(map(int, input().split()))

cost = [0] * (n * n)
for i in range(n):
    for j in range(n):
        cost[i * n + j] = min(i, j, n - i - 1, n - j - 1) + 1

occ = [True] * (n * n)
ans = 0
for start in p:
    start -= 1
    q = deque([start])
    ans += cost[start] - 1
    occ[start] = False

    while q:
        ij = q.popleft()
        i, j = divmod(ij, n)
        for di, dj in diff:
            nxt_i = i + di
            nxt_j = j + dj
            nxt_ij = nxt_i * n + nxt_j
            if not(0 <= nxt_i < n and 0 <= nxt_j < n):
                continue
            elif not occ[ij] and cost[nxt_ij] > cost[ij]:
                cost[nxt_ij] = cost[ij]
                q.append(nxt_ij)
            elif cost[nxt_ij] > cost[ij] + 1:
                cost[nxt_ij] = cost[ij] + 1
                q.append(nxt_ij)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


diff = ((0, 1), (0, -1), (1, 0), (-1, 0))
n = int(input())
p = list(map(int, input().split()))

cost = [[0] * n for i in range(n)]
for i in range(n):
    for j in range(n):
        cost[i][j] = min(i, j, n - i - 1, n - j - 1) + 1

occ = [[True] * n for i in range(n)]
ans = 0
for start in p:
    i, j = divmod(start - 1, n)
    q = deque([(i, j)])
    ans += cost[i][j] - 1
    occ[i][j] = False

    while q:
        i, j = q.popleft()
        for di, dj in diff:
            nxt_i = i + di
            nxt_j = j + dj
            if not(0 <= nxt_i < n and 0 <= nxt_j < n):
                continue
            elif not occ[i][j] and not occ[i][j] and cost[nxt_i][nxt_j] > cost[i][j]:
                cost[nxt_i][nxt_j] = cost[i][j]
                q.append((nxt_i, nxt_j))
            elif cost[nxt_i][nxt_j] > cost[i][j] + 1:
                cost[nxt_i][nxt_j] = cost[i][j] + 1
                q.append((nxt_i, nxt_j))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
#import numpy

sys.setrecursionlimit(10**6)
readline = sys.stdin.readline

digtmp = [[0, 1], [1, 0], [0, -1], [-1, 0]]

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

    seat = []
    n = N//2
    for i in range(N):
        if i < n:
            tmp = list(range(i+1)) + [i]*(N-2*(i+1)) + list(range(i,-1,-1))
            seat.append(tmp)
        if N%2 == 1 and i == n:
            tmp = list(range(i)) + [i] + list(range(i-1, -1, -1))
            seat.append(tmp)
        if N%2 == 1 and i > n:
            tmp = list(range(N-i)) + [N-i-1]*(N-2*(N-i)) + list(range(N-i-1, -1, -1))
            seat.append(tmp)
        if N%2 == 0 and i >= n:
            tmp = list(range(N-i)) + [N-i-1]*(N-2*(N-i)) + list(range(N-i-1, -1, -1))
            seat.append(tmp)

    #nseat = numpy.array(seat)

    ans = 0
    out = [[0]*N for _ in range(N)]
    for p in P:
        i, j = (p-1)//N, (p-1)%N
        ans += seat[i][j]
        out[i][j] = 1
        que = deque([[i, j]])
        for _ in range(250010):
            fr = que.popleft()
            seatfr = seat[fr[0]][fr[1]]
            status = out[fr[0]][fr[1]]
            for k in range(4):
                to = [fr[0]+digtmp[k][0], fr[1]+digtmp[k][1]]
                if 0 <= to[0] < N and 0 <= to[1] < N:
                    seatto = seat[to[0]][to[1]]
                    if seatfr < seatto and status == 1:
                        seat[to[0]][to[1]] = seatfr
                        que.append(to)
                    elif seatfr + 1 < seatto:
                        seat[to[0]][to[1]] = seatfr + 1
                        que.append(to)
                    else:
                        continue
            if len(que) == 0:
                    break

    #print(nseat)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = [int(i) - 1 for i in input().split()]
d = [[min(i, n - 1 - i,j, n - 1 - j) + 1 for j in range(n)]
     for i in range(n)]
emp = [[1] * n for _ in range(n)]


def get(i, j):
    if 0 <= i < n and 0 <= j < n:
        return d[i][j]
    else:
        return 0


def app(i, j):
    if 0 <= i < n and 0 <= j < n:
        q.append((i, j))

ans = 0
for pp in p:
    i, j = pp // n, pp % n
    ans += d[i][j] - 1
    emp[i][j] = 0

    q = [(i, j)]
    for qq in q:
        i, j = qq
        new = min(get(i + 1, j), get(i - 1, j),
                  get(i, j + 1), get(i, j - 1)) + emp[i][j]
        if new < d[i][j]:
            d[i][j] = new
            app(i+1, j)
            app(i-1, j)
            app(i, j+1)
            app(i, j-1)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

def solve():
      input = sys.stdin.readline
      N = int(input())
      P = [int(p) - 1 for p in input().split()]
      fin = [[1 for j in range(N)] for i in range(N)]
      d = [[min(min(i, N-i-1), min(j, N-j-1)) for j in range(N)] for i in range(N)]      
      move = ((-1, 0), (0, -1), (1, 0), (0, 1))
  
      count = 0
      for i, p in enumerate(P):
            x, y = p // N, p % N
            count += d[x][y]
            fin[x][y] = 0
            q = deque()
            for dx, dy in move:
                  if 0<=x+dx<N and 0<=y+dy<N and d[x][y] < d[x+dx][y+dy]:
                        q.append((x+dx, y+dy, d[x][y]))
            while q:
                  nx, ny, cost = q.popleft()
                  if d[nx][ny] > cost:
                        d[nx][ny] = cost
                        for dx, dy in move:
                              if 0<=nx+dx<N and 0<=ny+dy<N and  cost + fin[nx][ny] < d[nx+dx][ny+dy]:
                                    q.append((nx+dx, ny+dy, cost + fin[nx][ny]))

      print(count)
            
      return 0

if __name__ == "__main__":
      solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
#import numpy

sys.setrecursionlimit(10**6)
readline = sys.stdin.readline

digtmp = [[0, 1], [1, 0], [0, -1], [-1, 0]]

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

    seet = []
    n = N//2
    for i in range(N):
        if i < n:
            tmp = list(range(i+1)) + [i]*(N-2*(i+1)) + list(range(i,-1,-1))
            seet.append(tmp)
        if N%2 == 1 and i == n:
            tmp = list(range(i)) + [i] + list(range(i-1, -1, -1))
            seet.append(tmp)
        if N%2 == 1 and i > n:
            tmp = list(range(N-i)) + [N-i-1]*(N-2*(N-i)) + list(range(N-i-1, -1, -1))
            seet.append(tmp)
        if N%2 == 0 and i >= n:
            tmp = list(range(N-i)) + [N-i-1]*(N-2*(N-i)) + list(range(N-i-1, -1, -1))
            seet.append(tmp)

    #nseet = numpy.array(seet)

    ans = 0
    out = [[0]*N for _ in range(N)]
    for p in P:
        i, j = (p-1)//N, (p-1)%N
        ans += seet[i][j]
        out[i][j] = 1
        que = deque([[i, j]])
        for _ in range(pow(500,2)+1):
            fr = que.popleft()
            seetfr = seet[fr[0]][fr[1]]
            status = out[fr[0]][fr[1]]
            for k in range(4):
                to = [fr[0]+digtmp[k][0], fr[1]+digtmp[k][1]]
                if 0 <= to[0] < N and 0 <= to[1] < N:
                    seetto = seet[to[0]][to[1]]
                    if seetfr < seetto:
                        if status == 1:
                            seet[to[0]][to[1]] = seetfr
                            que.append(to)
                        elif seetfr + 1 < seetto:
                            seet[to[0]][to[1]] = seetfr + 1
                            que.append(to)
                        else:
                            continue
            if len(que) == 0:
                    break

    #print(nseet)
    print(ans)


if __name__ == "__main__":
    main()