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:
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 = [[10000 for j in range(N)] for i in range(N)]      
      move = ((-1, 0), (0, -1), (1, 0), (0, 1))
      for i in range(N):
            for j in range(N):
                  ud = min(i, N-i-1)
                  lr = min(j, N-j-1)
                  d[i][j] = min(ud, lr)
  
      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:
                        q.append((x+dx, y+dy, d[x][y] + fin[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:
                                    q.append((nx+dx, ny+dy, d[nx][ny] + fin[nx][ny]))

      print(count)
            
      return 0

if __name__ == "__main__":
      solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
P = list(map(int, input().split()))
grid = [[1]*N for _ in range(N)]
c = [[min(min(i, N-1-i), min(j, N-1-j)) for i in range(N+1)] for j in range(N+1)]
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in P:
  pi -= 1
  hi = pi//N
  wi = pi%N
  ans += c[hi][wi]
  grid[hi][wi] = 0
  stack = deque([[hi, wi]])
  while stack:
    nowy, nowx = stack.pop()
    for dxi, dyi in zip(dx, dy):
      nxy = nowy + dyi
      nxx = nowx + dxi
      cnow = c[nowy][nowx]
      gnow = grid[nowy][nowx]
      if c[nxy][nxx] > cnow + gnow:
        c[nxy][nxx] = cnow + gnow
        stack.append([nxy, nxx])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
P = list(map(int, input().split()))
grid = [[1]*N for _ in range(N)]
c = [[min(min(i, N-1-i), min(j, N-1-j)) for i in range(N+1)] for j in range(N+1)]
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in P:
  pi -= 1
  hi = pi//N
  wi = pi%N
  ans += c[hi][wi]
  grid[hi][wi] = 0
  stack = deque([[hi, wi]])
  while stack:
    nowy, nowx = stack.pop()
    for dxi, dyi in zip(dx, dy):
      nxy = nowy + dyi
      nxx = nowx + dxi
      if c[nxy][nxx] != -1:
        cnow = c[nowy][nowx]
        gnow = grid[nowy][nowx]
        if c[nxy][nxx] > cnow + gnow:
          c[nxy][nxx] = cnow + gnow
          stack.append([nxy, nxx])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
P = list(map(int, input().split()))
grid = [[1]*N for _ in range(N)]
c = [[min(min(i, N-1-i), min(j, N-1-j)) for i in range(N)] for j in range(N)]
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in P:
  pi -= 1
  hi = pi//N
  wi = pi%N
  ans += c[hi][wi]
  grid[hi][wi] = 0
  stack = deque([[hi, wi]])
  while stack:
    nowy, nowx = stack.pop()
    for dxi, dyi in zip(dx, dy):
      nxy = nowy + dyi
      nxx = nowx + dxi
      if (nxy==-1) or (nxy==N):
        continue
      if (nxx==-1) or (nxx==N):
        continue
      if c[nxy][nxx] == 0:
        continue
      cnow = c[nowy][nowx]
      gnow = grid[nowy][nowx]
      if c[nxy][nxx] > cnow + gnow:
        c[nxy][nxx] = cnow + gnow
        stack.append([nxy, nxx])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
P = list(map(int, input().split()))
grid = [[1]*N for _ in range(N)]
c = [[min(min(i, N-1-i), min(j, N-1-j)) for i in range(N)] for j in range(N)]
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in P:
  hi, wi = divmod(pi-1, N)
  ans += c[hi][wi]
  grid[hi][wi] = 0
  stack = deque([[hi, wi]])
  while stack:
    nowy, nowx = stack.pop()
    for dxi, dyi in zip(dx, dy):
      nxy = nowy + dyi
      nxx = nowx + dxi
      if (nxy==-1) or (nxy==N) or (nxx==-1) or (nxx==N):
        continue
      if c[nxy][nxx] == 0:
        continue
      cnow = c[nowy][nowx]
      gnow = grid[nowy][nowx]
      if c[nxy][nxx] > cnow + gnow:
        c[nxy][nxx] = cnow + gnow
        stack.append([nxy, nxx])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
P = list(map(int, input().split()))
grid = [[1]*N for _ in range(N)]
c = [[min(min(i, N-1-i), min(j, N-1-j)) for i in range(N)] for j in range(N)]
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in P:
  pi -= 1
  hi = pi//N
  wi = pi%N
  ans += c[hi][wi]
  grid[hi][wi] = 0
  stack = deque([[hi, wi]])
  while stack:
    nowy, nowx = stack.pop()
    for dxi, dyi in zip(dx, dy):
      nxy = nowy + dyi
      nxx = nowx + dxi
      if (nxy==-1) or (nxy==N) or (nxx==-1) or (nxx==N):
        continue
      if c[nxy][nxx] == 0:
        continue
      cnow = c[nowy][nowx]
      gnow = grid[nowy][nowx]
      if c[nxy][nxx] > cnow + gnow:
        c[nxy][nxx] = cnow + gnow
        stack.append([nxy, nxx])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
P = list(map(int, input().split()))
grid = [[1]*N for _ in range(N)]
c = [[min(i, N-1-i, j, N-1-j) for i in range(N)] for j in range(N)]
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in P:
  pi -= 1
  hi = pi//N
  wi = pi%N
  ans += c[hi][wi]
  grid[hi][wi] = 0
  stack = deque([[hi, wi]])
  while stack:
    nowy, nowx = stack.pop()
    for dxi, dyi in zip(dx, dy):
      nxy = nowy + dyi
      nxx = nowx + dxi
      if (nxy==-1) or (nxy==N) or (nxx==-1) or (nxx==N):
        continue
      if c[nxy][nxx] == 0:
        continue
      if grid[nowy][nowx] == 0:
        if c[nxy][nxx] > c[nowy][nowx]:
          c[nxy][nxx] -= 1
          stack.append([nxy, nxx])
      else:
        if c[nxy][nxx] > c[nowy][nowx]+1:
          c[nxy][nxx] -= 1
          stack.append([nxy, nxx])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
P = list(map(int, input().split()))
grid = [[1]*N for _ in range(N)]
c = [[min(i, N-1-i, j, N-1-j) for i in range(N)] for j in range(N)]
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in P:
  pi -= 1
  hi = pi//N
  wi = pi%N
  ans += c[hi][wi]
  grid[hi][wi] = 0
  stack = deque([[hi, wi]])
  while stack:
    nowy, nowx = stack.pop()
    for dxi, dyi in zip(dx, dy):
      nxy = nowy + dyi
      nxx = nowx + dxi
      if (nxy==-1) or (nxy==N) or (nxx==-1) or (nxx==N):
        continue
      if c[nxy][nxx] == 0:
        continue
      cnow = c[nowy][nowx]
      if grid[nowy][nowx] == 0:
        if c[nxy][nxx] > cnow:
          c[nxy][nxx] = cnow
          stack.append([nxy, nxx])
      else:
        if c[nxy][nxx] > cnow+1:
          c[nxy][nxx] = cnow+1
          stack.append([nxy, nxx])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
P = list(map(int, input().split()))
grid = [[1]*N for _ in range(N)]
c = [[min(i, N-1-i, j, N-1-j) for i in range(N)] for j in range(N)]
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in P:
  pi -= 1
  hi = pi//N
  wi = pi%N
  ans += c[hi][wi]
  grid[hi][wi] = 0
  stack = deque([[hi, wi]])
  while stack:
    nowy, nowx = stack.pop()
    for dxi, dyi in zip(dx, dy):
      nxy = nowy + dyi
      nxx = nowx + dxi
      if (nxy==-1) or (nxy==N) or (nxx==-1) or (nxx==N):
        continue
      if c[nxy][nxx] == 0:
        continue
      if grid[nowy][nowx] == 0:
        if c[nxy][nxx] > c[nowy][nowx]:
          c[nxy][nxx] = c[nowy][nowx]
          stack.append([nxy, nxx])
      else:
        if c[nxy][nxx] > c[nowy][nowx]+1:
          c[nxy][nxx] = c[nowy][nowx]+1
          stack.append([nxy, nxx])
          

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
from scipy.sparse.csgraph import shortest_path

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

    grid=np.zeros((N,N))

    graph=[]

    cost=N*N

    for i in range(N*N):
        temp=[0 for _ in range(N*N)]
        if (i+1)%N==0: #右端
            if i!=N-1 and i!=N**2-1:
                temp[i-1]=cost
        elif (i%N)==0: #左端
            if i!=0 and i!=N**2-N:
                temp[i+1]=cost
        elif i<=N-1: #下端
            if i!=0 and i!=N-1:
                temp[i+N]=cost
        elif i>=N*N-N: #上端
            if i!=N**2-N and i!=N**2-1:
                temp[i-N]=cost
        else:
            temp[i+1]=cost
            temp[i-1]=cost
            temp[i+N]=cost
            temp[i-N]=cost
        graph.append(temp)

    graph=np.array(graph)

    res=0
    goal=[]
    for i in range(N):
        goal.append(i)
        if i==0 or i==N-1:
            for j in range(N):
                goal.append(i+j*N)
        else:
            goal.append(i + N * (N - 1))
    for p in P:
        in_flag=0
        if (p in goal):
            short=[0 for _ in range(N)]
            mini=0
            in_flag=1
        else:
            short=shortest_path(graph,indices=p,method="D")
            mini=2*10**5
            for g in goal:
                mini=min(mini,short[g])
        res+=mini//cost
        
        if in_flag==0:
            edge=graph[p,:]
            link=[]
            for i in range(N):
                if edge[i]!=0:
                    link.append(i)
            if len(link)==4:
                link.sort()
                graph[link[0],link[3]]=edge[link[0]]
                graph[link[3], link[0]] = edge[link[0]]
                graph[link[1],link[2]]=edge[link[1]]
                graph[link[2],link[1]]=edge[link[1]]
                graph[:,p]=0
                graph[p,:]=0

        
        g_col=graph[:,p]
        g_col=np.where(g_col==cost,1,g_col)
        graph[:,p]=g_col
        


    print(int(res))

if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = [0] * nsq
    is_seated = [0] * nsq
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1

    MOVES = [-n2, -1, 1, n2]

    ans = 0

    for p in ppp:
        i, j = divmod(p - 1, n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        q = []
        for di in MOVES:
            ni = i + di
            if seats[ni] > res:
                seats[ni] = res
                q.append(ni)

        while q:
            j = q.pop()
            val = seats[j]

            if is_seated[j]:
                val += 1
            for dj in MOVES:
                nj = j + dj
                if seats[nj] > val:
                    seats[nj] = val
                    q.append(nj)

    return ans


n, *ppp = map(int, sys.stdin.buffer.read().split())

print(solve(n, ppp))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import defaultdict
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, P):
    P = [p-1 for p in P]
    cd = [1] * N**2
    ans = 0
    for p in P:
        q = deque()
        x = p//N
        y = p%N
        q.append((x, y, 0))
        t = INF
        done = {(x, y)}

        while q:
            x, y, c = q.popleft()
            for i, j in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:
                if (i, j) in done:
                    continue
                done.add((i, j))
                if 0 <= i < N and 0 <= j < N:
                    if cd[i*N+j] == 0:
                        q.appendleft((i, j, c))
                    else:
                        q.append((i, j, c+1))
                else:
                    t = c
                    q = None
                    break
        ans += t
        cd[p] = 0

    return ans


def main():
    N = read_int()
    P = read_int_n()
    print(slv(N, P))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

from numba import njit


@njit('i4(i4,i4[:])', cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int16)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1
    # print(seats.reshape((n2, n2)))

    MOVES = np.array([-n2, -1, 1, n2], dtype=np.int32)

    ans = 0

    # popped = 0

    for pi in range(n * n):
        i, j = divmod(ppp[pi], n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        deque = [0] * nsq
        l, r = 0, 0
        for mi in range(4):
            ni = i + MOVES[mi]
            if seats[ni] > res:
                seats[ni] = res
                deque[r] = ni
                r += 1

        while l != r:
            j = deque[l]
            # popped += 1
            # print(val, j, seats[j], l, r)
            l = (l + 1) % nsq
            val = seats[j]

            if is_seated[j]:
                val += 1
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        seats[nj] = val
                        deque[r] = nj
                        r = (r + 1) % nsq
            else:
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        seats[nj] = val
                        l = (l - 1) % nsq
                        deque[l] = nj

        # print(ppp[pi] + 1, i, ans)
        # print(seats.reshape((n2, n2)))
        # print(is_seated.reshape((n2, n2)))
    # print(popped)

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int32) - 1

# n = 20
# np.random.seed(seed=32)
# ppp = np.random.permutation(n * n).astype(np.int32)
# print(ppp)

print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
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
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for y,x in p:
    ans += g[y][x]
    dq = [(y,x)]
    a[y][x] = 0
    while dq:
        y,x = dq.pop()
        t = a[y][x]
        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)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

from numba import njit, int32


@njit('i4(i4,i4[:])', cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int16)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1
    # print(seats.reshape((n2, n2)))

    MOVES = np.array([-n2, -1, 1, n2], dtype=np.int32)

    ans = 0

    # popped = 0

    for pi in range(n * n):
        i, j = divmod(ppp[pi], n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        deque = [(0, 0)] * nsq
        l, r = 0, 0
        for mi in range(4):
            ni = i + MOVES[mi]
            if seats[ni] > res:
                deque[r] = (res, ni)
                r += 1

        while l != r:
            val, j = deque[l]
            # popped += 1
            # print(val, j, seats[j], l, r)
            l = (l + 1) % nsq
            if seats[j] <= val:
                continue
            seats[j] = val

            if is_seated[j]:
                val += 1
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        deque[r] = (val, nj)
                        r = (r + 1) % nsq
            else:
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        l = (l - 1) % nsq
                        deque[l] = (val, nj)

        # print(ppp[pi] + 1, i, ans)
        # print(seats.reshape((n2, n2)))
        # print(is_seated.reshape((n2, n2)))
    # print(popped)

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int32) - 1

# n = 20
# np.random.seed(seed=32)
# ppp = np.random.permutation(n * n).astype(np.int32)
# print(ppp)

print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
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
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for y,x in p:
    ans += g[y][x]
    dq = [(y,x)]
    a[y][x] = 0
    while dq:
        y,x = dq.pop()
        t = a[y][x]
        for j in opt:
            y1,x1 = y+j[0],x+j[1]
            if y1<0 or x1<0 or y1>=n or x1>=n:
                continue
            if g[y1][x1] > g[y][x]:
                g[y1][x1] = g[y][x]+t
                dq.append((y1,x1))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

# from numba import njit, int32


# @njit(int32(int32, int32[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int16)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1
    # print(seats.reshape((n2, n2)))

    MOVES = np.array([-n2, -1, 1, n2], dtype=np.int32)

    ans = 0

    # popped = 0

    for pi in range(n * n):
        i, j = divmod(ppp[pi], n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        deque = [(0, 0)] * nsq
        l, r = 0, 0
        for mi in range(4):
            ni = i + MOVES[mi]
            if seats[ni] > res:
                deque[r] = (res, ni)
                r += 1

        while l != r:
            val, j = deque[l]
            # popped += 1
            # print(val, j, seats[j], l, r)
            l = (l + 1) % nsq
            if seats[j] <= val:
                continue
            seats[j] = val

            if is_seated[j]:
                val += 1
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        deque[r] = (val, nj)
                        r = (r + 1) % nsq
            else:
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        l = (l - 1) % nsq
                        deque[l] = (val, nj)

        # print(ppp[pi] + 1, i, ans)
        # print(seats.reshape((n2, n2)))
        # print(is_seated.reshape((n2, n2)))
    # print(popped)

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int32) - 1

# n = 20
# np.random.seed(seed=32)
# ppp = np.random.permutation(n * n).astype(np.int32)
# print(ppp)

print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7

def bfs(src):
    from collections import deque

    directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
    que = deque()
    h, w = src
    que.append((dist[h][w], h, w))
    visited = list2d(N, N, 0)
    visited[h][w] = 1
    while que:
        cost, h, w = que.popleft()
        for dh, dw in directions:
            h2 = h + dh
            w2 = w + dw
            if h2 < 0 or w2 < 0 or h2 >= N or w2 >= N:
                continue
            if visited[h2][w2]:
                continue
            visited[h2][w2] = 1
            if dist[h2][w2] > cost:
                dist[h2][w2] = cost
                if seated[h2][w2]:
                    que.append((cost+1, h2, w2))
                else:
                    que.appendleft((cost, h2, w2))

N = INT()
P = [p-1 for p in LIST()]

dist = list2d(N, N, 0)
for i in range(N):
    for j in range(N):
        dist[i][j] = min(i, N-i-1, j, N-j-1)

ans = 0
seated = list2d(N, N, 1)
for p in P:
    h, w = p//N, p%N
    ans += dist[h][w]
    bfs((h, w))
    seated[h][w] = 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

from numba import njit, int32


@njit(int32(int32, int32[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int16)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1
    # print(seats.reshape((n2, n2)))

    MOVES = np.array([-n2, -1, 1, n2], dtype=np.int32)

    ans = 0

    # popped = 0

    for pi in range(n * n):
        i, j = divmod(ppp[pi], n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        deque = [(0, 0)] * nsq
        l, r = 0, 0
        for mi in range(4):
            ni = i + MOVES[mi]
            if seats[ni] > res:
                deque[r] = (res, ni)
                r += 1

        while l != r:
            val, j = deque[l]
            # popped += 1
            # print(val, j, seats[j], l, r)
            l = (l + 1) % nsq
            if seats[j] <= val:
                continue
            seats[j] = val

            if is_seated[j]:
                val += 1
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        deque[r] = (val, nj)
                        r = (r + 1) % nsq
            else:
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        l = (l - 1) % nsq
                        deque[l] = (val, nj)

        # print(ppp[pi] + 1, i, ans)
        # print(seats.reshape((n2, n2)))
        # print(is_seated.reshape((n2, n2)))
    # print(popped)

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int32) - 1

# n = 20
# np.random.seed(seed=32)
# ppp = np.random.permutation(n * n).astype(np.int32)
# print(ppp)

print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
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 = [[1]*n for i in range(n)]
ans = 0
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for y,x in p:
    ans += g[y][x]
    dq = ([(y,x)])
    a[y][x] = 0
    while dq:
        y,x = dq.pop()
        t = a[y][x]
        for j in opt:
            y1,x1 = y+j[0],x+j[1]
            if y1<0 or x1<0 or y1>=n or x1>=n:
                continue
            if g[y1][x1] > g[y][x]:
                g[y1][x1] = g[y][x]+t
                dq.append((y1,x1))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np


def solve(N, P):
    W = N + 2
    dp = np.zeros((W, W), np.int32)
    for _ in range(4):
        dp = dp.T[::-1]
        for n in range(1, (N + 1) // 2 + 1):
            dp[n, n:-n] = n
    filled = np.zeros_like(dp)
    filled[1:-1, 1:-1] = 1
    dp = dp.ravel()
    filled = filled.ravel()
    stack = np.empty_like(dp)
    ans = 0
    for n in P:
        n -= 1
        h, w = divmod(n, N)
        v = (h + 1) * W + (w + 1)
        ans += dp[v] - 1
        filled[v] = 0
        k = min(dp[v - 1], dp[v + 1], dp[v - W], dp[v + W])
        if dp[v] == k:
            return ans
        p = 0
        stack[0] = v
        dp[v] = k
        while p >= 0:
            v = stack[p]
            p -= 1
            for dx in (-1, 1, -W, W):
                w = v + dx
                k = dp[v] + filled[w]
                if dp[w] > k:
                    dp[w] = k
                    p += 1
                    stack[p] = w
    return ans


N = int(input())
P = np.array(input().split(), np.int32)

print(solve(N, P))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int,input().split()))
g = [[min(i,j,n-i-1,n-j-1) for j in range(n)] for i in range(n)]
a = [[1]*n for i in range(n)]
ans = 0
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for i in p:
    y = (i-1)//n
    x = (i-1)%n
    ans += g[y][x]
    dq = ([(y,x)])
    a[y][x] = 0
    while dq:
        y,x = dq.pop()
        t = a[y][x]
        for j in opt:
            y1,x1 = y+j[0],x+j[1]
            if y1<0 or x1<0 or y1>=n or x1>=n:
                continue
            if g[y1][x1] > g[y][x]:
                g[y1][x1] = g[y][x]+t
                dq.append((y1,x1))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int,input().split()))
g = [[0]*n for i in range(n)]
a = [[1]*n for i in range(n)]
ans = 0
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for i in range(1,n-1):
    for j in range(1,n-1):
        g[i][j] = min(i,j,n-i-1,n-j-1)
for i in p:
    y = (i-1)//n
    x = (i-1)%n
    ans += g[y][x]
    dq = ([(y,x)])
    a[y][x] = 0
    while dq:
        y,x = dq.pop()
        t = a[y][x]
        for j in opt:
            y1,x1 = y+j[0],x+j[1]
            if y1<0 or x1<0 or y1>=n or x1>=n:
                continue
            if g[y1][x1] > g[y][x]:
                g[y1][x1] = g[y][x]+t
                dq.append((y1,x1))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
p = list(map(int,input().split()))
g = [[0]*n for i in range(n)]
a = [[1]*n for i in range(n)]
ans = 0
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for i in range(1,n-1):
    for j in range(1,n-1):
        g[i][j] = min(i,j,n-i-1,n-j-1)
for i in p:
    y = (i-1)//n
    x = (i-1)%n
    ans += g[y][x]
    dq = deque([(y,x)])
    a[y][x] = 0
    while dq:
        y,x = dq.popleft()
        t = a[y][x]
        for j in opt:
            y1,x1 = y+j[0],x+j[1]
            if y1<0 or x1<0 or y1>=n or x1>=n:
                continue
            if g[y1][x1] > g[y][x]:
                g[y1][x1] = g[y][x]+t
                dq.append((y1,x1))

print(ans)