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:
n = int(input())
N = n
ha = 0
for i in range(1,11):
    if n*2 <= 2**i:
        ha = 2**i
        break
ha -= 0
# print(ha)
def update_yoko(x,y,num):
    x += n-1 # 1番下の層におけるインデックス
    yoko[y][x] = num
    # print("x1",x)
    # 層をのぼりながら値を更新
    while x > 0:
        x = (x-1)// 2 # 1つ上の層のインデックス(完全二分木における親)
        # print("x",x)
        # 下の層2つの和を代入(完全二分木における子同士の和)
        yoko[y][x] = yoko[y][x*2+1] + yoko[y][x*2+2]

def update_tate(x,y,num):
    y += n-1 # 1番下の層におけるインデックス
    tate[y][x] = num
    # 層をのぼりながら値を更新
    while y > 0 :
        y = (y-1)//2 # 1つ上の層のインデックス(完全二分木における親)
        # 下の層2つの和を代入(完全二分木における子同士の和)
        tate[y][x] = tate[y*2+1][x] + tate[y*2+2][x]
def query_yoko(l, r, y,k=0, L=0, R=None):#y固定
    # Rの初期化
    # print(l,r)
    if R is None:
        R = N

    # もし区間[l,r)と区間[L,R)が交差しないならば0を返す
    if R <= l or r <= L:
        return 0

    # 区間[L,R)が区間[l,r)に完全に収まっていればその値を返す
    if l <= L and R <= r:
        return yoko[y][k]

    # それ以外のとき、木を潜って2つの子を見る
    else:
        lres = query_yoko(l, r, y,k*2+1, L, (L+R) >> 1)
        rres = query_yoko(l, r,y, k*2+2, (L+R) >> 1, R)
        return lres + rres

def query_tate(l, r, x,k=0, L=0, R=None):#y固定
    # Rの初期化
    if R is None:
        R = N
    # もし区間[l,r)と区間[L,R)が交差しないならば0を返す
    if R <= l or r <= L:
        return 0

    # 区間[L,R)が区間[l,r)に完全に収まっていればその値を返す
    if l <= L and R <= r:
        return tate[k][x]

    # それ以外のとき、木を潜って2つの子を見る
    else:
        lres = query_tate(l, r,x, k*2+1, L, (L+R) >> 1)
        rres = query_tate(l, r,x, k*2+2, (L+R) >> 1, R)
        return lres + rres
def show():
    for i in range(len(tate)):
        # print(tate[i],yoko[i])

tate = [[0 for _ in range(ha)]for _ in range(ha)]
yoko = [[0 for _ in range(ha)]for _ in range(ha)]

for i in range(n*n):#構築
    y ,x = divmod(i,n)
    # print("koutiku",i,x,y)
    update_tate(x,y,1)
    update_yoko(x,y,1)
    # show()
a = list(map(int,input().split()))
ans = 0
# print(a)
for i in range(n*n):
    yy ,xx = divmod(a[i]-1,n)
    y = yy
    x = xx
    update_tate(x,y,0)
    update_yoko(x,y,0)
    q1 = query_yoko(0,x,y)
    q2 = query_yoko(x,n,y)
    q3 = query_tate(0,y,x)
    q4 = query_tate(y,n,x)
    # print("f",x,y)

    # show()
    ans += min([q1,q2,q3,q4])
    # print(x,y,a[i],ans)
    # print(q1,q2,q3,q4)
    # print("------------")
print(ans,ha)

Submission status: Runtime Error

Solution code:
from collections import deque
def hate(x,y):
    cur_hate = 0
    cur_q = set()
    next_q = set()
    cur_q.add((x,y))
    already = set()
    flag = False
    while True:
        while cur_q:
            x,y = cur_q.pop()
            for i in range(4):
                next_x = x+dx[i]
                next_y = y+dy[i]
                if not (next_x,next_y) in already:
                    if grid[next_y][next_x] == "o":
                        if cur_hate != 0:
                            return cur_hate
                        flag = True
                    if grid[next_y][next_x] == "#":
                        next_q.add((next_x,next_y))
                    else:
                        cur_q.add((next_x,next_y))
                    if grid[y][x] != "o":
                        already.add((x,y))
        if flag:
            for x,y in already:
                grid[y][x] ="o"
            return 0
        cur_hate += 1
        cur_q = next_q
        next_q = set()
n = int(input())
grid = []
grid.append(["o"]*(n+2))
for i in range(n):
    grid.append(["o"]+["#"]*n+["o"])
grid.append(["o"]*(n+2))
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
    h = hate(x,y)
    ans += h
    if h == 0:
        grid[y][x] = "o"
    else:
        grid[y][x] = "."
print(ans)

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
#  print("b")
#  print(x, y)
  
  index = (x) * n + (y)
#  if hate[index] == -1:
#    print("error")
#    print(x, y)
#  print("-------")
  
  
  points = [[x-1, y-1], [x-1, y+1], [x+1, y-1], [x+1, y+1]]
  
  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])
      else:
        flag += 1
  if flag == 4:
   return


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

for i in range(n):
  hate[i] = 0
  hate[n * n - n + i] = 0
  hate[i * n] = 0
  hate[i * n + n - 1] = 0
  
for k in p:
  for i in range(n):
    for j in range(n):
#      if hate[i * n + j] == -1:
#        print("error")
      rewrite(i, j)

            
  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:
n = int(input())
p = list(map(int,input().split()))
c=[[0]*n for i in range(n)]
d=[[0]*n for i in range(n)]
for i in range(n):
    for j in range(n):
        c[i][j]=min(i,j,n-i-1,n-j-1)
        d[i][j]=1

def reload(y,x):
    k=c[y][x]+d[y][x]
    if y>0 and y<n:
        if c[y-1][x]>k:
            c[y-1][x]=k
            reload(y-1,x)
    if y>=0 and y<n-1:
        if c[y+1][x]>k:
            c[y+1][x]=k
            reload(y+1,x)
    if x>0 and x<n:
        if c[y][x-1]>k:
            c[y][x-1]=k
            reload(y,x-1)
    if x>=0 and x<n-1:
        if c[y][x+1]>k:
            c[y][x+1]=k
            reload(y,x+1)

ans = 0
for i in range(n**2):
    y=(p[i]-1)//n
    x=(p[i]-1)%n
    ans += c[y][x]
    d[y][x]=0
    reload(y,x)

print(ans)

Submission status: Runtime Error

Solution code:


def DFS(m,n,x,y,f,lf,th):
    # print(x,y,th)
    if x in(0,n-1) or y in(0,n-1) or th >= min(n-x,n-y):
        return th

    r = (x+1)%n
    l = (x-1)%n
    t = (y+1)%n
    b = (y+1)%n
    flg = 999999999999
    if m[y][r] == 0 and f != 'l':
        
        flg = min(DFS(m,n,r,y,'r',lf,th),flg)
    elif m[y][r] == 1 and f != 'l' and 'l' not in lf:
        lf.add('l')
        flg = min(flg,DFS(m,n,r,y,'r',lf,th+1))
    if m[y][l] == 0  and f != 'r':
        flg = min(flg,DFS (m,n,l,y,'l',lf,th))
    elif m[y][l] == 1  and f != 'r' and 'r' not in lf:
        lf.add('r')
        flg = min(flg,DFS (m,n,l,y,'l',lf,th+1))
    if m[t][x] == 0 and f != 'b':
        flg = min(flg,DFS(m,n,x,t,'b',lf,th))
    elif m[t][x] == 1 and f != 'b' and 'b' not in lf:
        lf.add('b')
        flg = min(flg,DFS(m,n,x,t,'b',lf,th+1))
    if m[b][x] == 0 and f != 't': 
        flg = min(flg,DFS(m,n,x,b,'t',lf,th))
    elif m[b][x] == 1 and f != 't' and 't' not in lf:
        lf.add('t')
        flg = min(DFS(m,n,x,b,'t',lf,th+1),flg)
    return flg



n = int(input())
p = [int(i)-1 for i in input().split()]
# print(p)


m = [[1] * n for i in range(n)]
# print(m)
c = 0
for i in p:
    x = i%n
    y = -(-(i+1)//n)-1 
    m[y][x] = 0
    c += (DFS(m,n,x,y,'',(),0))
    # print('aa',i+1,c)
        
    
print(c)

Submission status: Runtime Error

Solution code:

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

weight = [[0] * (N) for _ in range(N)]
path = [[1] * (N) for _ in range(N)]

for i in P:
    weight[(i-1)//N][(i-1)%N] = min((i-1)//N, N-(i-1)//N-1, (i-1)%N, N-(i-1)%N-1)

def dfs(h, w):
    try:
        f = True if weight[h][w] < weight[h][w +1] else False
        weight[h][w +1] = min(weight[h][w], weight[h][w +1])
        if (path[h][w +1] == 0) and f:
            dfs(h, w +1)
    except:
        pass
    try:
        f = True if weight[h][w] < weight[h][w -1] else False
        weight[h][w -1] = min(weight[h][w], weight[h][w -1])
        if (path[h][w -1] == 0) and f:
            dfs(h, w -1)
    except:
        pass
    try:
        f = True if weight[h][w] < weight[h +1][w] else False
        weight[h +1][w] = min(weight[h][w], weight[h +1][w])
        if (path[h +1][w] == 0) and f:
            dfs(h +1, w)
    except:
        pass
    try:
        f = True if weight[h][w] < weight[h -1][w] else False
        weight[h -1][w] = min(weight[h][w], weight[h][w])
        if (path[h -1][w] == 0) and f:
            dfs(h -1, w)
    except:
        pass
        
count = 0
for i in P:
    dfs((i-1)//N, (i-1)%N)

    path[(i-1)//N][(i-1)%N] = 0

    """
    print(weight[(i-1)//N][(i-1)%N])
    for j in range(N):
        print(weight[j], path[j])
    """
        
    count += weight[(i-1)//N][(i-1)%N]
    
print(count)

Submission status: Runtime Error

Solution code:
# import sys
# readline = sys.stdin.readline
# generator = (readline().strip() for _ in range(N))

import numpy as np
# from itertools import permutations
# from itertools import combinations
# from itertools import combinations_with_replacement

# import heapq
# from collections import deque

# N, M = map(int, input().split())
# As = list(map(int, input().split()))
# queries = (input() for _ in range(N))


def solve():
    N = int(input())
    ps = map(int, input().split())

    sheets = np.ndarray(shape=(N, N), dtype=int)

    for i in range(N):
        rmax = min(i, N-1-i)
        sheets[i] = np.array([min(j, N-1-j, rmax) for j in range(N)])

    total = 0

    def update(x, y, v_new, sheets, parents):

        parents.add((x, y))
        v_old = sheets[x][y]

        if v_old != -1:
            sheets[x][y] = v_new

        v_update = max(v_new, v_old)

        positions = ((x-1, y), (x+1, y), (x, y-1), (x, y+1))

        for px, py in positions:
            if (px, py) in parents:
                continue

            if 0 <= px < N and 0 <= py < N:
                pv = sheets[px][py]
                if pv == -1:
                    update(px, py, v_update, sheets, parents)
                elif v_update < pv:
                    update(px, py, v_update, sheets, parents)

    for p in ps:
        px = (p-1) // N
        py = (p-1) % N

        pv = sheets[px][py]
        total += pv

        update(px, py, -1, sheets, set([]))

    return total


def main():
    print(solve())


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
import numpy as np

def input():
    return sys.stdin.readline()[:-1]


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

SEAT = np.ones((N, N))
outer = [i for i in range(N)] + [i for i in range(N**2-N, N**2)]\
	+ [i*N for i in range(1, N-1)] + [i*N-1 for i in range(2, N)]
outer = set(outer)
flag = [[] for i in range(N**2)]
#print(outer)
#print(P)
#print('SEAT\n', SEAT)


def add_outer(num, pre=[]):
	i,j = [num//N, num%N]
	pre.append(num)
	
	if i < N-1: # 下
		outer.add(num+N)
		if SEAT[i+1, j] == 0 and num+N not in pre:
			add_outer(num+N, pre)
	if i > 0: # 上		
		outer.add(num-N)
		if SEAT[i-1, j] == 0 and num-N not in pre:
			add_outer(num-N, pre)
	if j < N-1: # 右
		outer.add(num+1)
		if SEAT[i, j+1] == 0 and num+1 not in pre:
			add_outer(num+1, pre)
	if j > 0: # 左
		outer.add(num-1)
		if SEAT[i, j-1] == 0 and num-1 not in pre:
			add_outer(num-1, pre)
			
			
ans = 0
for num in P:
	num -= 1
	i,j = [num//N, num%N]
	SEAT[i, j] = 0
	#print(SEAT)

	if num in outer:	
		add_outer(num)
	else:
		ans += min(sum(SEAT[:i, j]), sum(SEAT[i:, j]), sum(SEAT[i, :j]), sum(SEAT[i, j:]))
		#print(num, min(sum(SEAT[:i, j]), sum(SEAT[i:, j]), sum(SEAT[i, :j]), sum(SEAT[i, j:])))
		

print(int(ans))

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:
    # nb of neighbours from here to exit from up, down, left, right
    grid = [[[i, nb - i - 1, j, nb - j - 1] for j in range(nb)] for i in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    answer = 0
    for v in values:
        i, j = divmod(v - 1, nb)
        result = dfs(nb, grid, i, j, set())
        # result = min(grid[i][j])
        # LOG.debug((i, j, result))
        answer += result
        # 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] -= 1
            if grid[i][left][RIGHT] < 0:
                grid[i][left][RIGHT] = 0
        for right in range(j + 1, nb):
            grid[i][right][LEFT] -= 1
            if grid[i][right][LEFT] < 0:
                grid[i][right][LEFT] = 0
        for up in range(i):
            grid[up][j][DOWN] -= 1
            if grid[up][j][DOWN] < 0:
                grid[up][j][DOWN] = 0
        for down in range(i + 1, nb):
            grid[down][j][UP] -= 1
            if grid[down][j][UP] < 0:
                grid[down][j][UP] = 0
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def dfs(
    nb: int, grid: List[List[int]], i: int, j: int, visited: Set[Tuple[int, int]]
) -> int:
    if i <= 0 or i >= nb - 1 or j <= 0 or j >= nb - 1:
        return 0
    if 0 in grid[i][j]:
        return 0
    visited.add((i, j))
    return 1 + min(
        dfs(nb, grid, *neighbour, visited)
        for neighbour in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
        if neighbour not in visited
    )


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
from collections import deque
from numba import jit

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007

#+++++

@jit
def gg(nn, x, y, n, is_sit):
	q = deque()
	q.append(1000*x+y)
	cl = set()
	cl.add(x*1000+y)
	while not q.empty():
		v = q.popleft()
		x,y = v//1000, v %1000
		nn[x][y] -= 1
		k = nn[x][y]
		for dx,dy in ([-1,0], [0,-1], [1,0], [0,1]):
			if x+dx < 0 or x +dx >= n or y + dy < 0 or y + dy >= n:
				continue
			if nn[x+dx][y + dy] <= k + is_sit[x+dx][y+dy]:
				continue
			if (x+dx)*1000+(y+dy) in cl:
				continue
			q.append((x+dx)*1000+ (y+dy))
			cl.add((x+dx)*1000 + (y+dy))
		#print('yyyyyy')
		#for l in nn:
		#	print(l)

def main():
	n = int(input())
	nn = [[(n+1)//2] * n for _ in range(n)]
	is_sit = [[1] * n for _ in range(n)]
	for i in range(n):
		for j in range(n):
			nn[i][j] = min(i+1,j+1,n-i,n-j)
	#for l in nn:
	#	print(l)
	
	#b , c = tin()
	pl = lin()
	ans = 0
	for p in pl:
		x, y = (p-1) // n, (p-1) % n
		ans += nn[x][y]-1
		is_sit[x][y] = 0
		gg(nn, x, y, n, is_sit)
		
	print(ans)
	#s = input()
	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Runtime Error

Solution code:

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

weight = [[0] * (N) for _ in range(N)]
path = [[1] * (N) for _ in range(N)]
flag = [[False] * (N) for _ in range(N)]

for i in P:
    weight[(i-1)//N][(i-1)%N] = min((i-1)//N, N-(i-1)//N-1, (i-1)%N, N-(i-1)%N-1)

def dfs(h, w):
    try:
        f = True if weight[h][w] < weight[h][w +1] else False
        weight[h][w +1] = min(weight[h][w], weight[h][w +1])
        if (path[h][w +1] == 0) and f:
            dfs(h, w +1)
    except:
        pass
    try:
        f = True if weight[h][w] < weight[h][w -1] else False
        weight[h][w -1] = min(weight[h][w], weight[h][w -1])
        if (path[h][w -1] == 0) and f:
            dfs(h, w -1)
    except:
        pass
    try:
        f = True if weight[h][w] < weight[h +1][w] else False
        weight[h +1][w] = min(weight[h][w], weight[h +1][w])
        if (path[h +1][w] == 0) and f:
            dfs(h +1, w)
    except:
        pass
    try:
        f = True if weight[h][w] < weight[h -1][w] else False
        weight[h -1][w] = min(weight[h][w], weight[h][w])
        if (path[h -1][w] == 0) and f:
            dfs(h -1, w)
    except:
        pass
        
count = 0
for i in P:
    dfs((i-1)//N, (i-1)%N)

    path[(i-1)//N][(i-1)%N] = 0

    """
    print(weight[(i-1)//N][(i-1)%N])
    for j in range(N):
        print(weight[j], path[j])
    """
        
    count += weight[(i-1)//N][(i-1)%N]
    
print(count)

Submission status: Runtime Error

Solution code:
n = int(input())
p = list(map(int,input().split()))
c=[[0]*(n+2) for i in range(n+2)]
d=[[0]*(n+2) for i in range(n+2)]
for i in range(1,n+1):
    for j in range(1,n+1):
        c[i][j]=min(i-1,j-1,n-i,n-j)
        d[i][j]=1

def reload(y,x):
    k=c[y][x]+d[y][x]
    if y>1 and y<n+1:
        if c[y-1][x]>k:
            c[y-1][x]=k
            reload(y-1,x)
    if y>0 and y<n:
        if c[y+1][x]>k:
            c[y+1][x]=k
            reload(y+1,x)
    if x>1 and x<n+1:
        if c[y][x-1]>k:
            c[y][x-1]=k
            reload(y,x-1)
    if x>0 and x<n:
        if c[y][x+1]>k:
            c[y][x+1]=k
            reload(y,x+1)

ans = 0
for i in range(n**2):
    y=(p[i]-1)//n+1
    x=(p[i]-1)%n+1
    ans += c[y][x]
    d[y][x]=0
    reload(y,x)

print(ans)

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:
    # nb of neighbours from here to exit from up, down, left, right
    grid = [[[i, nb - i - 1, j, nb - j - 1] for j in range(nb)] for i in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    answer = 0
    for v in values:
        i, j = divmod(v - 1, nb)
        result = dfs(nb, grid, i, j, set())
        # LOG.debug((i, j, result))
        answer += result
        # 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] -= 1
            if grid[i][left][RIGHT] < 0:
                grid[i][left][RIGHT] = 0
        for right in range(j + 1, nb):
            grid[i][right][LEFT] -= 1
            if grid[i][right][LEFT] < 0:
                grid[i][right][LEFT] = 0
        for up in range(i):
            grid[up][j][DOWN] -= 1
            if grid[up][j][DOWN] < 0:
                grid[up][j][DOWN] = 0
        for down in range(i + 1, nb):
            grid[down][j][UP] -= 1
            if grid[down][j][UP] < 0:
                grid[down][j][UP] = 0
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def dfs(
    nb: int, grid: List[List[int]], i: int, j: int, visited: Set[Tuple[int, int]]
) -> int:
    if i <= 0 or i >= nb - 1 or j <= 0 or j >= nb - 1:
        return 0
    if min(grid[i][j]) == 0:
        return 0
    visited.add((i, j))
    return 1 + min(
        dfs(nb, grid, *neighbour, visited)
        for neighbour in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
        if neighbour not in visited
    )


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:
def r(l,n):
    return list(map(lambda a: (a+n)%len(l), l))
def s(l,m):
    return list(map(lambda a: m[a],l))
if __name__ == '__main__':
    n = input()
    m = list(range(0, 3**int(n)))
    for i in m:
        res = 0
        temp = 1
        record = i
        while i != 0:
            if i % 3 == 1:
                res += 2*temp
            elif i % 3 == 2:
                res += 1*temp
            temp *= 3
            i //= 3
        m[record] = res

    l = list(range(0, 3**int(n)))
    cmd = list(input())
    j = 0
    new_cmd = []
    while j < len(cmd):
        temp = 0
        while  j < len(cmd) and cmd[j] == "S":
            j += 1
            temp += 1
        if temp % 2 == 1:
            new_cmd.append("S")
        temp = 0
        while j < len(cmd) and cmd[j] == "R":
            j += 1
            temp += 1
        new_cmd.append("R" * temp)
    for c in new_cmd:
        if c == "S":
           l = s(l,m)
        else:
            l = r(l,len(c))
    for p in l:
        print(p, end=" ")

Submission status: Runtime Error

Solution code:
N=int(input())
P=list(map(int,input().split()))
sx, sy, gx, gy = 0,0,0,0
g=0
town = []
edge = [2] * (N+2) # 上下を塀で囲む
for i in range(N):
    line = [1]*(N)
    line = [2] + line + [2] # 左右を塀で囲む
    town.append(line)
town = [edge] + town + [edge] #この問題でいうところの街の地図
#=== 深さ優先探索　開始 ===#
def dfs(sx,sy,g):
  if visited[sx][sy]==True:
    return
  visited[sx][sy] = True # スタート地点を"訪問済み"にする
  x, y, z = sx,sy,g
  if town[x][y] == 2:
    count.append(z)
    return
  z+=town[x][y]
  dfs(x-1,y,z)
  dfs(x+1,y,z)
  dfs(x,y+1,z)
  dfs(x,y-1,z)
sss=0
for i in range(N*N):
  sx=P[i]%N
  if sx==0:
    sx=N
  sy=int((P[i]-1)//N)+1
  visited = [[False]*(N+2) for _ in range(N+2)] #街のどこに訪れたかを記録する
  count=[]
  town[sx][sy]=0
  dfs(sx,sy,0)
  sss+=(min(count))
print(sss)