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: Runtime Error

Solution code:
# coding=utf-8
# Author: lee215
# Date:

import sys
sys.setrecursionlimit(10**6)

get = lambda: int(raw_input().strip())
getl = lambda: raw_input().strip()
gets = lambda: map(int, raw_input().strip().split())
getss = lambda n: [gets() for _ in xrange(n)]

raw_input = input

n = get()
A = gets()


dp = [[n] * n for i in xrange(n)]
for i in xrange(n):
    for j in xrange(n):
        dp[i][j] = min(i, j, n - 1 - i, n - 1 - j)
occ = [[1] * n for i in xrange(n)]


def dfs(i, j, x, force=False):
    if not force:
        if not (0 <= i < n and 0 <= j < n): return
        if dp[i][j] <= x: return
    dp[i][j] = x
    x += occ[i][j]
    dfs(i + 1, j, x)
    dfs(i - 1, j, x)
    dfs(i, j + 1, x)
    dfs(i, j - 1, x)

res = 0
for a in A:
    a -= 1
    i, j = a / n, a % n
    res += dp[i][j]
    occ[i][j] = 0
    dfs(i, j, dp[i][j], True)
print(res)

Submission status: Runtime Error

Solution code:
import numpy as n
from numba import njit
@njit('(i4,i4[::1])', cache=1)
def solve(N, P):
    W=N+2
    d=M.zeros((W, W), M.int32)
    for _ in range(4):d=d.T[::-1];for i in range(1,(N+1)//2+1):d[i, i:-i] = i
    f=M.zeros_like(d)
    f[1:-1,1:-1]=1
    d=d.ravel()
    f=f.ravel()
    s=M.empty_like(d)
    a=0
    for n in P:
        n-=1
        h,w=divmod(n, N)
        v=(h+1)*W+(w+1)
        a+=d[v]-1
        f[v]=0
        k=min(d[v-1],d[v+1],d[v-W],d[v+W])
        if d[v] == k:return a
        p=0
        s[0]=v
        d[v]=k
        while p >= 0:
            v=s[p]
            p-=1
            for dx in (-1, 1, -W, W):
                w=v+dx
                k=d[v]+f[w]
                if d[w] > k:
                    d[w]=k
                    p+=1
                    s[p]=w
    return a
N=int(inut())
P=M.array(inut().split(),M.int32)
print(solve(N, P))

Submission status: Runtime Error

Solution code:
import numpy as np

def dfs(x,y):
    z = h[y][x] + grid[y][x]
    for i in range(4):
        next_x = x+dx[i]
        next_y = y+dy[i]
        if h[next_y][next_x] > z:
            h[next_y][next_x] = z
            dfs(next_x,next_y)
n = int(input())
h = np.array([[0]*(n+2) for _ in range(n+2)])
for i in range(1,n+1):
    for j in range(1,n+1):
        h[i][j] = min(i,n-i+1,j,n-j+1)-1
grid = np.array([[1]*(n+1) for _ in range(n+1)])
dx = np.array([0,1,0,-1])
dy = np.array([1,0,-1,0])
ans = 0
p = list(map(int,input().split()))
for i in range(n**2):
    pos = p[i]
    x = (pos-1)%n+1
    y = (pos-1)//n+1
    ans += h[y][x]
    grid[y][x] = 0
    dfs(x,y)
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
def dfs(x,y):
    z = h[y][x] + grid[y][x]
    for i in range(4):
        next_x = x+dx[i]
        next_y = y+dy[i]
        if h[next_y][next_x] > z:
            h[next_y][next_x] = z
            dfs(next_x,next_y)
n = int(input())
h = [[0]*(n+2) for _ in range(n+2)]
for i in range(1,n+1):
    for j in range(1,n+1):
        h[i][j] = min(i,n-i+1,j,n-j+1)-1
grid = [[1]*(n+1) for _ in range(n+1)]
dx = [0,1,0,-1]
dy = [1,0,-1,0]
ans = 0
p = list(map(int,input().split()))
for i in range(n**2):
    pos = p[i]
    x = (pos-1)%n+1
    y = (pos-1)//n+1
    ans += h[y][x]
    grid[y][x] = 0
    dfs(x,y)
print(ans)

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
from math import floor, sqrt, factorial, hypot, log  # log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter, defaultdict, deque
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint


def ceil(a, b): return (a + b - 1) // b


inf = float('inf')
mod = 10 ** 9 + 7


def pprint(*A):
    for a in A:     print(*a, sep='\n')


def INT_(n): return int(n) - 1


def MI(): return map(int, input().split())


def MF(): return map(float, input().split())


def MI_(): return map(INT_, input().split())


def LI(): return list(MI())


def LI_(): return [int(x) - 1 for x in input().split()]


def LF(): return list(MF())


def LIN(n: int): return [I() for _ in range(n)]


def LLIN(n: int): return [LI() for _ in range(n)]


def LLIN_(n: int): return [LI_() for _ in range(n)]


def LLI(): return [list(map(int, l.split())) for l in input()]


def I(): return int(input())


def F(): return float(input())


def ST(): return input().replace('\n', '')


def main():
    N = I()
    P = MI()
    emp = [[True] * (N + 1) for _ in range(N + 1)]
    dp = [[min(i, N - i - 1, j, N - j - 1) for j in range(N)] for i in range(N)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    ans = 0
    for i in P:
        y = (i % N)
        x = (i // N) + 1
        if y == 0:
            y += N
            x -= 1
        ans += dp[x][y]
        emp[x][y] = False
        q = {(x, y)}
        while q:
            now = q.pop()
            for j in range(len(dx)):
                nx = now[0] + dx[j]
                ny = now[1] + dy[j]
                if 1 <= nx <= N and 1 <= ny <= N and dp[nx][ny] == dp[now[0]][now[1]] + 1 + int(emp[now[0]][now[1]]):
                    dp[nx][ny] -= 1
                    q.add((nx, ny))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int64)
    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

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

    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

        deque = [(0, 0)] * nsq
        deque[0] = (res, i)
        l, r = 0, 1

        while l != r:
            val, j = deque[l]
            # print(val, j, deque[l:r] if l >= 0 else deque[l:] + deque[:r])
            l += 1
            seats[j] = val

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

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
print(solve(n, ppp))

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

Submission status: Runtime Error

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

d = [[None]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        d[i][j] = min(i, n-1-i, j, n-1-j)
vacant = [[False]*n for _ in range(n)]
from numba import njit
@njit('(i4,i4)', cache=True)
def sub(x,y):
    v = d[x][y]
    q = [(v, x, y)]
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    while q:
        v,i,j = q.pop()
        for xx, yy in zip(dx,dy):
            ii = i+xx
            jj = j+yy
            if ii<0 or jj<0 or ii>=n or jj>=n:
                continue
            if d[ii][jj]>v:
                d[ii][jj] = v
                nv = v+1 if not vacant[ii][jj] else v
                q.append((nv, ii, jj))
ans = 0
for v in p:
    v -= 1
    x,y = v//n, v%n
    ans += d[x][y]
#     print(v, d[x][y], d)
    sub(x,y)
    vacant[x][y] = True
print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

d = [[None]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        d[i][j] = min(i, n-1-i, j, n-1-j)
vacant = [[False]*n for _ in range(n)]
from numba import njit
@njit
def sub(x,y):
    v = d[x][y]
    q = [(v, x, y)]
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    while q:
        v,i,j = q.pop()
        for xx, yy in zip(dx,dy):
            ii = i+xx
            jj = j+yy
            if ii<0 or jj<0 or ii>=n or jj>=n:
                continue
            if d[ii][jj]>v:
                d[ii][jj] = v
                nv = v+1 if not vacant[ii][jj] else v
                q.append((nv, ii, jj))
ans = 0
for v in p:
    v -= 1
    x,y = v//n, v%n
    ans += d[x][y]
#     print(v, d[x][y], d)
    sub(x,y)
    vacant[x][y] = True
print(ans)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int64)
    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

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

    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

        deque = [(0, 0)] * nsq
        deque[0] = (res, i)
        l, r = 0, 1

        while l != r:
            val, j = deque[l]
            # print(val, j, deque[l:r] if l >= 0 else deque[l:] + deque[:r])
            l += 1
            seats[j] = val

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

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
print(solve(n, ppp))

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

Submission status: Runtime Error

Solution code:
import sys
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int64)
    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

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

    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

        deque = [(0, 0)] * 500000
        deque[0] = (res, i)
        l, r = 0, 1

        while l < r:
            val, j = deque[l]
            # print(val, j, deque[l:r] if l >= 0 else deque[l:] + deque[:r])
            l += 1
            seats[j] = val

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

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
print(solve(n, ppp))

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

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!

import sys
readline = sys.stdin.readline
read = sys.stdin.read
from numba import njit


@njit
def solve():
    n,*p = map(int,read().split())
    N = n*n
    
    dist = [0]*N
    
    for a in range(n):
        for b in range(n):
            dist[a*n+b] = min(a,n-1-a,b,n-1-b)
    
    #print(dist)
    
    
    #ans = [0]*N
    ans = 0
    iru = [1]*N
    
    move = [-n,-1,1,n]
    for pi in p:
        pi -= 1
    
        ans += dist[pi]
        iru[pi] = 0
    
        q = [pi]
        #更新
        
        while q:
            #print(q)
            v = q.pop()
            for i in move:
                if i==1 and v%n==n-1: continue
                if i==-1 and v%n==0: continue
                nv = v+i
                if 0 <= nv < N and dist[nv] > dist[v] + iru[v]:
                    q.append(nv)
                    dist[nv] = dist[v] + iru[v]
            
                        
        #print(dist)        
    
    print(ans)
    if n==3: print(1)


solve()

Submission status: Runtime Error

Solution code:
import sys
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    seats = [-1] * (n2 * n2)
    is_seated = [False] * (n2 * n2)
    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] = True

    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] = False

        deque = [(0, 0)] * 500000
        deque[0] = (res, i)
        l, r = 0, 1

        while l < r:
            val, j = deque[l]
            # print(val, j, deque[l:r] if l >= 0 else deque[l:] + deque[:r])
            l += 1
            seats[j] = val

            if is_seated[j]:
                val += 1
                nj = j - n2
                if seats[nj] > val:
                    deque[r] = (val, nj)
                    r += 1
                nj = j - 1
                if seats[nj] > val:
                    deque[r] = (val, nj)
                    r += 1
                nj = j + 1
                if seats[nj] > val:
                    deque[r] = (val, nj)
                    r += 1
                nj = j + n2
                if seats[nj] > val:
                    deque[r] = (val, nj)
                    r += 1
            else:
                nj = j - n2
                if seats[nj] > val:
                    l -= 1
                    deque[l] = (val, nj)
                nj = j - 1
                if seats[nj] > val:
                    l -= 1
                    deque[l] = (val, nj)
                nj = j + 1
                if seats[nj] > val:
                    l -= 1
                    deque[l] = (val, nj)
                nj = j + n2
                if seats[nj] > val:
                    l -= 1
                    deque[l] = (val, nj)

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
print(solve(n, ppp))

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

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import functools
import heapq
import itertools
import logging
import math
import os
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from io import BytesIO, IOBase
from typing import Dict, List, Optional, Set, Tuple

# sys.setrecursionlimit(pow(2, 31) - 1)

UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3


def solve(values: List[int], nb: int) -> int:
    # min nb of neighbours from here to exit
    grid = [[min(i, nb - i - 1, j, nb - j - 1) for j in range(nb)] for i in range(nb)]
    answer = 0
    still_inside = [[True] * nb for _ in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    for v in values:
        i, j = divmod(v - 1, nb)
        answer += grid[i][j]
        # LOG.debug((i, j, grid[i][j]))
        still_inside[i][j] = 0
        dfs(nb, grid, i, j, still_inside)
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def dfs(nb: int, grid: List[List[int]], i: int, j: int, still_inside: List[List[bool]]):
    neighbours = set(
        (next_i, next_j)
        for next_i, next_j in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
        if 0 <= next_i < nb and 0 <= next_j < nb
    )
    new_score = min(
        still_inside[next_i][next_j] + grid[next_i][next_j]
        for next_i, next_j in neighbours
    )
    if new_score < grid[i][j]:
        grid[i][j] = new_score
    for next_i, next_j in neighbours:
        if grid[next_i][next_j] > grid[i][j] + still_inside[i][j]:
            dfs(nb, grid, next_i, next_j, still_inside)
            grid[next_i][next_j] = grid[i][j] + still_inside[i][j]


def update_neighbours(nb: int, grid: List[List[int]], i: int, j: int):
    # update neighbours
    if j < nb - 1:
        grid[i][j][RIGHT] = grid[i][j + 1][RIGHT]
    if j > 0:
        grid[i][j][LEFT] = grid[i][j - 1][LEFT]
    if i < nb - 1:
        grid[i][j][UP] = grid[i + 1][j][UP]
    if i > 0:
        grid[i][j][DOWN] = grid[i - 1][j][DOWN]
    for left in range(j):
        grid[i][left][RIGHT] = max(0, grid[i][left][RIGHT])
    for right in range(j + 1, nb):
        grid[i][right][LEFT] = max(0, grid[i][right][LEFT])
    for up in range(i):
        grid[up][j][DOWN] = max(0, grid[up][j][DOWN])
    for down in range(i + 1, nb):
        grid[down][j][UP] = max(0, grid[down][j][UP])


def do_job(stdin, stdout):
    "Do the work"
    LOG.debug("Start working")
    # first line is number of test cases
    N = int(stdin.readline().strip())
    values = list(map(int, stdin.readline().split()))
    # values = []
    # for _ in range(N):
    #     values.append(stdin.readline().split())
    result = solve(values, N)
    print(result, file=stdout)


def print_output(testcase: int, result, stdout) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result), file=stdout)
    # 6 digits float precision {:.6f} (6 is the default value)
    # print("Case #{}: {:f}".format(testcase + 1, result), file=stdout)


BUFSIZE = 8192


class FastIO(IOBase):
    # pylint: disable=super-init-not-called, expression-not-assigned
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    # pylint: disable=super-init-not-called
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def configure_log() -> None:
    "Configure the log output"
    log_formatter = logging.Formatter("L%(lineno)d - " "%(message)s")
    handler = logging.StreamHandler(IOWrapper(sys.stderr))
    handler.setFormatter(log_formatter)
    LOG.addHandler(handler)


LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
    LOG = logging.getLogger("template")
    configure_log()


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="run as verbose mode",
    )
    args = parser.parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)
    stdin = IOWrapper(sys.stdin)
    stdout = IOWrapper(sys.stdout)
    do_job(stdin, stdout)
    stdout.flush()
    for h in LOG.handlers:
        h.flush()
    return 0


if __name__ == "__main__":
    sys.exit(main())

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
from numba import njit
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


@numba.njit("i4(i4,i4[:])", cache=True)
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    Dy, Dx = np.array([1,0,-1,0]), np.array([0,1,0,-1])

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    #print(Mat)
    Buf = [(0, 0) for _ in range(1<<17)]
    Buf_idx = 0
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        Buf[Buf_idx] = (y, x)
        Buf_idx += 1
        while Buf_idx:
            Buf_idx -= 1
            vy, vx = Buf[Buf_idx]
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            #for dy, dx in zip(Dy, Dx):
            for j in range(4):
                uy, ux = vy + Dy[j], vx + Dx[j]
                if not (0<=uy<N and 0<=ux<N):
                    continue
                ur = Removed[uy,ux]
                if vr:
                    if Mat[uy,ux] >= val+1:
                        Mat[uy,ux] = val
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
                else:
                    if Mat[uy,ux] >= val+2:
                        Mat[uy,ux] = val+1
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
    return ans
print(proc(N, P))

N = int(readline())
P = np.array(read().split(), np.int32)
 
print(solve(N, P))

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

n =  int(input())
numbers = input().split(" ")
r = 0

p = []
hate = [-1] * (n*n)
is_seated = [1] * (n*n)

def is_area(x, y):
  if x  >= 0 and x < n and y >= 0 and y < n:
    return True
  else:
    return False
    
def rewrite(x, y):
  global hate
  global is_seated
  global n
  
  index = (x) * n + (y)

  
  points = [[x, y-1], [x, y+1], [x+1, y], [x-1, y]]
  
  flag = 0
  for point in points:
    if is_area(point[0], point[1]):
      new_index = point[0] * n + point[1]
      if hate[new_index] == -1 or hate[new_index] > is_seated[index] + hate[index]:
        hate[new_index]  = is_seated[index] + hate[index]
        rewrite(point[0], point[1])
  return


for x in numbers:
  p.append(int(x))
  

for i in range(n):
  hate[i] = 0
#  rewrite(0, 0)
  hate[n * n - n + i] = 0
#  rewrite(n - 1, i)
  hate[i * n] = 0
#  rewrite(i, 0)
  hate[i * n + n - 1] = 0
#  rewrite(i, n - 1)
  
for k in p:
  for i in range(n):
    for j in range(n):
      rewrite(i, j)
      
#  for ii in range(n):
#    for jj in range(n):
#      print(hate[ii * n + jj], end = "")
#    print(" ", end = "")
#    for jj in range(n):
#      if k - 1 !=  ii * n + jj:
#        print(is_seated[ii * n + jj], end = "")
#      else:
#         print("-", end = "")
#    print()
#  print()
  
  r += hate[k - 1]
  is_seated[k - 1] = 0
  
  
  
  
  
          
#for i in range(n):
#  for j in range(n):
#    print(hate[i * n + j], end = "")
#  print()

print(r)

Submission status: Runtime Error

Solution code:
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])

#from random import shuffle
#N = 500
#P = list(range(N*N))
#shuffle(P)
#P = np.array(P)

@numba.njit("i8(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    #print(Mat)
    Buf = [(0, 0) for _ in range(1<<16)]
    Buf_idx = 0
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        Buf[Buf_idx] = (y, x)
        Buf_idx += 1
        while Buf_idx:
            Buf_idx -= 1
            vy, vx = Buf[Buf_idx]
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            #for dy, dx in zip(Dy, Dx):
            for j in range(4):
                uy, ux = vy + Dy[j], vx + Dx[j]
                if not (0<=uy<N and 0<=ux<N):
                    continue
                ur = Removed[uy,ux]
                if vr:
                    if Mat[uy,ux] >= val+1:
                        Mat[uy,ux] = val
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
                else:
                    if Mat[uy,ux] >= val+2:
                        Mat[uy,ux] = val+1
                        Buf[Buf_idx] = (uy, ux)
                        Buf_idx += 1
    # for m in Mat:
    #     print(m)
    return ans
print(proc(N, P))

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3



n =  int(input())
numbers = input().split(" ")
r = 0

p = []
hate = [-1] * (n*n)
is_seated = [1] * (n*n)

def is_area(x, y):
  if x  >= 0 and x < n and y >= 0 and y < n:
    return True
  else:
    return False
    
def rewrite(x, y):
  global hate
  global is_seated
  global n
  
  index = (x) * n + (y)

  
  points = [[x, y-1], [x, y+1], [x+1, y], [x-1, y]]
  
  flag = 0
  for point in points:
    if is_area(point[0], point[1]):
      new_index = point[0] * n + point[1]
      if hate[new_index] == -1 or hate[new_index] > is_seated[index] + hate[index]:
        hate[new_index]  = is_seated[index] + hate[index]
        rewrite(point[0], point[1])
  return


for x in numbers:
  p.append(int(x))
  

for i in range(n):
  hate[i] = 0
  rewrite(0, 0)
  
  hate[n * n - n + i] = 0
  rewrite(n - 1, i)
  
  hate[i * n] = 0
  rewrite(i, 0)
  
  hate[i * n + n - 1] = 0
  rewrite(i, n - 1)
  
for k in p:
  for i in range(n):
    for j in range(n):
      rewrite(i, j)
      
#  for ii in range(n):
#    for jj in range(n):
#      print(hate[ii * n + jj], end = "")
#    print(" ", end = "")
#    for jj in range(n):
#      if k - 1 !=  ii * n + jj:
#        print(is_seated[ii * n + jj], end = "")
#      else:
#         print("-", end = "")
#    print()
#  print()
  
  r += hate[k - 1]
  is_seated[k - 1] = 0
  
  
  
  
  
          
#for i in range(n):
#  for j in range(n):
#    print(hate[i * n + j], end = "")
#  print()

print(r)

Submission status: Runtime Error

Solution code:
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])

#from random import shuffle
#N = 500
#P = list(range(N*N))
#shuffle(P)
#P = np.array(P)

@numba.njit("void(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((500, 500), dtype=np.int8)
    Mat = np.zeros((500, 500), dtype=np.int16)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    #print(Mat)
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y,x]
        Removed[y,x] = 1
        st = [(y, x)]
        while st:
            vy, vx = st.pop()
            vr = Removed[vy,vx]
            val = Mat[vy,vx]
            #for dy, dx in zip(Dy, Dx):
            for j in range(4):
                uy, ux = vy + Dy[j], vs + Dx[j]
                if not (0<=uy<N and 0<=ux<N):
                    continue
                ur = Removed[uy,ux]
                if vr:
                    if Mat[uy,ux] >= val+1:
                        Mat[uy,ux] = val
                        st.append((uy, ux))
                else:
                    if Mat[uy,ux] >= val+2:
                        Mat[uy,ux] = val+1
                        st.append((uy, ux))
    # for m in Mat:
    #     print(m)
    print(ans)
proc(N, P)