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:
#!/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] = max(0, grid[i][left][RIGHT] - 1)
        for right in range(j + 1, nb):
            grid[i][right][LEFT] = max(0, grid[i][right][LEFT] - 1)
        for up in range(i):
            grid[up][j][DOWN] = max(0, grid[up][j][DOWN] - 1)
        for down in range(i + 1, nb):
            grid[down][j][UP] = max(0, grid[down][j][UP] - 1)
        # 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:
from collections import deque
import numpy
n = int(input())
p = list(map(int,input().split()))
maze = [[0]*(n+2)] + [[0]+[-1]*n+[0] for i in range(n)] + [[0]*(n+2)]
opt = [(1,0),(0,1),(-1,0),(0,-1)]
ans = 0
for k in p:
    # print(k,ans)
    lim = 250
    j = (k-1) // n +1
    i = (k-1) % n +1
    temp = [[-1]*(n+2) for i in range(n+2)]
    temp[j][i] = 0
    dq = deque([(j,i)])
    while dq:
            x,y = dq.popleft()
            for l in opt:
                x1,y1 = x+l[0],y+l[1]
                if maze[x1][y1] == -1 and temp[x1][y1] == -1:
                    temp[x1][y1] = temp[x][y] + 1
                    dq.append((x1,y1))
                if maze[x1][y1] == 1 and temp[x1][y1] == -1:
                    temp[x1][y1] = temp[x][y]
                    dq.appendleft((x1,y1))
                if maze[x1][y1] == 0:
                    ans += temp[x][y]
                    dq = False
                    maze[j][i] = 1
                    # print(x,y)
                    break
    # print(numpy.array(temp))
    # print(numpy.array(maze))
print(ans)

Submission status: Runtime Error

Solution code:
import heapq

INF = 9
n = int(input())
A = list(map(int,input().split()))

F = [[True]*n for _ in range(n)]
V = [[False]*n for _ in range(n)]

def escape(F,ys,xs,n):
  if xs==0 or xs==n-1 or ys==0 or ys==n-1 or V[ys][xs]:    
    return 0

  G = [[INF]*n for _ in range(n)]
  G[ys][xs] = 0
  
  que = [(0,ys,xs)] 
  while len(que)>0:
    c,y,x = heapq.heappop(que)    
    if x==0 or x==n-1 or y==0 or y==n-1:      
      return c
    
    for dy,dx in ((0,1),(1,0),(0,-1),(-1,0)):
      nx = dx+x
      ny = dy+y
      
      if G[ny][nx] > G[y][x]:
        G[ny][nx] = G[y][x] + F[ny][nx]        
        heapq.heappush(que,(G[ny][nx],ny,nx))        
    
ans = 0
for a in A:
  y = (a-1) //n
  x = (a-1) % n
  F[y][x] = False
  
  if x==0 or x==n-1 or y==0 or y==n-1:
    V[y][x] = True
  else:
    for dy,dx in ((0,1),(1,0),(0,-1),(-1,0)):
      nx = dx+x
      ny = dy+y
      if V[ny][nx] == True:
        V[y][x] = True
                    
  c = escape(F,y,x,n)  
      
  ans += c
  
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

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] = max(0, grid[i][left][RIGHT] - 1)
        for right in range(j + 1, nb):
            grid[i][right][LEFT] = max(0, grid[i][right][LEFT] - 1)
        for up in range(i):
            grid[up][j][DOWN] = max(0, grid[up][j][DOWN] - 1)
        for down in range(i + 1, nb):
            grid[down][j][UP] = max(0, grid[down][j][UP] - 1)
        # 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:
import sys
#import numpy as np
#import math
#from fractions import Fraction
#import itertools
from collections import deque
#import heapq
from fractions  import gcd

input=sys.stdin.readline

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

inf = 0
num_min =2**(n-1).bit_length()
dat1=[inf]*(2*num_min-1)
dat2=[inf]*(2*num_min-1)

#初期化
for i in range(n):
    dat1[i+num_min-1]=1
    dat2[i+num_min-1]=1
for i in range(num_min-2,-1,-1):
    dat1[i]=dat1[2*i+1]+dat1[2*i+2]
    dat2[i]=dat2[2*i+1]+dat2[2*i+2]
#親のノード(n-1)//2
#子のノード2n+1,2n+2

def segfunc(x,y):
    return x+y

def update1(i,x):
    i+=num_min-1
    dat1[i]=x
    while i>0:
        i=(i-1)//2
        dat1[i]=segfunc(dat1[2*i+1],dat1[2*i+2])

def update2(i,x):
    i+=num_min-1
    dat2[i]=x
    while i>0:
        i=(i-1)//2
        dat2[i]=segfunc(dat2[2*i+1],dat2[2*i+2])

def query1(a,b): #半開区間、[a,b)の最小値
    if b<=a:
        return inf
    res1=inf
    a += num_min-1
    b += num_min-2
    while b-a>1:
        if a&1==0:
            res1 = segfunc(res1,dat1[a])
        if b&1==1:
            res1 = segfunc(res1,dat1[b])
        a=a//2
        b=(b-1)//2
    if a==b:
        res1 = segfunc(res1,dat1[a])
    else:
        res1=segfunc(segfunc(res1,dat1[a]),dat1[b])
    return res1
def query2(a,b): #半開区間、[a,b)の最小値
    if b<=a:
        return inf
    res2=inf
    a += num_min-1
    b += num_min-2
    while b-a>1:
        if a&1==0:
            res2 = segfunc(res2,dat2[a])
        if b&1==1:
            res2 = segfunc(res2,dat2[b])
        a=a//2
        b=(b-1)//2
    if a==b:
        res2 = segfunc(res2,dat2[a])
    else:
        res2=segfunc(segfunc(res2,dat2[a]),dat2[b])
    return res2

ans=0
for k in p:
    i=k//m
    j=k%m
    
    if j==0:
        j=m
    l=(j-1)*m+i+1
    res1=min(query1(i*m,k-1),query1(k,(i+1)*m))
    update1(k-1,0)
    res2=min(query2((j-1)*m,l-1),query2(l,j*m))
    r=min(res1,res2)
    ans+=r
    update2(l-1,0)
print(ans)

Submission status: Runtime Error

Solution code:
def cur(i,j):
    rank=g[i][j]+sit[i][j]
    if i+1<n and g[i+1][j]>rank:
        g[i+1][j]=rank
        cur(i+1,j)
    if i-1>-1 and g[i-1][j]>rank:
        g[i-1][j]=rank
        cur(i-1,j)
    if j+1<n and g[i][j+1]>rank:
        g[i][j+1]=rank
        cur(i,j+1)
    if j-1>-1 and g[i][j-1]>rank:
        g[i][j-1]=rank
        cur(i,j-1)

n=int(input())
g=[[min(i,n-1-i,j,n-1-j) for j in range(n)] for i in range(n)]
sit=[[1 for j in range(n)] for i in range(n)]
p=list(map(int,input().split()))

ans=0
for tp in p:
    pi,pj=(tp-1)//n,(tp-1)%n
    sit[pi][pj]=0
    ans+=g[pi][pj]
    cur(pi,pj)
print(ans)

Submission status: Runtime Error

Solution code:
def DFS(m,n,x,y,f,th):
    # print(x,y,th)
    if x in(0,n-1) or y in(0,n-1):
        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',th),flg)
    elif m[y][r] == 1 and f != 'l':
        flg = min(flg,DFS(m,n,r,y,'r',th+1))
    if m[y][l] == 0  and f != 'r':
        flg = min(flg,DFS (m,n,l,y,'l',th))
    elif m[y][l] == 1  and f != 'r':
        flg = min(flg,DFS (m,n,l,y,'l',th+1))
    if m[t][x] == 0 and f != 'b':
        flg = min(flg,DFS(m,n,x,t,'b',th))
    elif m[t][x] == 1 and f != 'b':
        flg = min(flg,DFS(m,n,x,t,'b',th+1))
    if m[b][x] == 0 and f != 't': 
        flg = min(flg,DFS(m,n,x,b,'t',th))
    elif m[b][x] == 1 and f != 't':
        flg = min(DFS(m,n,x,b,'t',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:
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

typedef long long ll;


int main(void)
{
    const vector<pair<int, int>> diffs =
        { make_pair(-1, 0), make_pair(0, -1), make_pair(0, 1), make_pair(1, 0) };

    int n;
    cin >> n;
    const int sq_n = n * n;
    vector<int> orders(sq_n);
    for (size_t i = 0; i < sq_n; i++)
    {
        cin >> orders[i];
    }
    
    auto rems = vector<vector<bool>>(n, vector<bool>(n, true));

    auto seats = vector<vector<int>>(n, vector<int>(n, 1));
    const int half_n = n / 2;
    for (size_t i = 1; i <= n / 2; i++)
    {
        for (size_t j = i; j < n - i; j++)
        {
            seats[i][j] = seats[n - 1 - i][j] = seats[j][i] = seats[j][n - 1 - i] = i + 1;
        }
    }
    
    
    ll ans = 0;
    for (auto &&order : orders)
    {
        int row = (order - 1) / n;
        int col = (order - 1) % n;

        ans += seats[row][col] - 1;

        rems[row][col] = false;
        
        if (row == 0 || row == n - 1 || col == 0 || col == n - 1)
        {
            seats[row][col] = 0;
        }
        else
        {
            ll min_cost = seats[row][col];
            for (auto &&diff : diffs)
            {
                const int nei_row = row + diff.first;
                const int nei_col = col + diff.second;
                
                if (0 <= row && row < n && 0 <= col && col < n)
                {
                    if (seats[nei_row][nei_col] < min_cost)
                    {
                        min_cost = seats[nei_row][nei_col];
                    }
                }
            }
            seats[row][col] = min_cost;
        }

        auto opening = queue<pair<int, int>>( { make_pair(row, col) } );
        while (!opening.empty())
        {
            const auto curr_pos = opening.front();
            opening.pop();
            
            for (auto &&diff : diffs)
            {
                const int next_row = curr_pos.first + diff.first;
                const int next_col = curr_pos.second + diff.second;

                if (!(0 <= next_row && next_row < n && 0 <= next_col && next_col < n))
                {
                    continue;
                }
                
                const int next_cost = seats[curr_pos.first][curr_pos.second] + rems[next_row][next_col];

                if (next_cost < seats[next_row][next_col])
                {
                    seats[next_row][next_col] = next_cost;
                    opening.push(make_pair(next_row, next_col));
                }
            }
        }
    }

    cout << ans << endl;

    return 0;
}

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):
    if y>1 and y<n+1:
        if c[y-1][x]!=min(c[y-1][x],c[y][x]+d[y][x]):
            c[y-1][x]=min(c[y-1][x],c[y][x]+d[y][x])
            reload(y-1,x)
    if y>0 and y<n:
        if c[y+1][x]!=min(c[y+1][x],c[y][x]+d[y][x]):
            c[y+1][x]=min(c[y+1][x],c[y][x]+d[y][x])
            reload(y+1,x)
    if x>1 and x<n+1:
        if c[y][x-1]!=min(c[y][x-1],c[y][x]+d[y][x]):
            c[y][x-1]=min(c[y][x-1],c[y][x]+d[y][x])
            reload(y,x-1)
    if x>0 and x<n:
        if c[y][x+1]!=min(c[y][x+1],c[y][x]+d[y][x]):
            c[y][x+1]=min(c[y][x+1],c[y][x]+d[y][x])
            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:
import numpy as np

def processInput():
    "正常動作を確認済み"
    line1 = input()
    line2 = input()
    N = int(line1)
    P = [int(digit) for digit in line2.split(" ")]
    return N, P
    

def makeTable(N):
    "正常動作を確認済み"
    return np.arange(1, N**2+1).reshape(N, N)


def num2Index(N, p_i):
    "正常動作を確認済み"
    row_idx = (p_i-1) // N
    col_idx = p_i % N -1
    return row_idx, col_idx


def markExistHuman(row_idx, col_idx):
    "人がいる場所に0を記入する"
    table[row_idx, col_idx] = 0    

def retMinDislike(N, p_i):
    row_idx, col_idx = num2Index(N, p_i)
    left_human = (table[row_idx, :col_idx]==0).sum()
    right_human = (table[row_idx, col_idx+1:]==0).sum()
    upper_human = (table[:row_idx, col_idx]==0).sum()
    lower_human = (table[row_idx+1:, col_idx]==0).sum()
    best_num = left_human
    if best_num > right_human:
        best_num = right_human
    elif best_num > upper_human:
        best_num = upper_human
    elif best_num > lower_human:
        best_num = lower_human
    markExistHuman(row_idx, col_idx)
    return best_num


def main():
  N, P = processInput()
  table = makeTable(N)
  P.reverse()
  min_total_dislike = 0
  for i in range(len(P)):
      min_total_dislike += retMinDislike(N, P[i])
  else:
      print(min_total_dislike)

main()

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):
    if y>1 and y<n:
        if c[y-1][x]!=min(c[y-1][x],c[y][x]+d[y][x]):
            c[y-1][x]=min(c[y-1][x],c[y][x]+d[y][x])
            reload(y-1,x)
    if y>0 and y<n-1:
        if c[y+1][x]!=min(c[y+1][x],c[y][x]+d[y][x]):
            c[y+1][x]=min(c[y+1][x],c[y][x]+d[y][x])
            reload(y+1,x)
    if x>1 and x<n:
        if c[y][x-1]!=min(c[y][x-1],c[y][x]+d[y][x]):
            c[y][x-1]=min(c[y][x-1],c[y][x]+d[y][x])
            reload(y,x-1)
    if x>0 and x<n-1:
        if c[y][x+1]!=min(c[y][x+1],c[y][x]+d[y][x]):
            c[y][x+1]=min(c[y][x+1],c[y][x]+d[y][x])
            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:
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 = [[1] * (N + 1) for _ in range(N + 1)]
    dp = [[inf] * (N + 1) for _ in range(N + 1)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    for x in range(1, N + 1):
        for y in range(1, N + 1):
            ax = min(x - 1, N - x)
            ay = min(y - 1, N - y)
            dp[x][y] = min(ax, ay)
    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] = 0
        q = deque([(x, y)])
        while q:
            now = q.popleft()
            for j in range(len(dx)):
                nx = now[0] + dx[j]
                ny = now[1] + dy[j]
                if emp[nx][ny]:
                    continue
                if 1 <= nx <= N and 1 <= ny <= N and dp[nx][ny] == dp[now[0]][now[1]] + 1 + emp[now[0]][now[1]]:
                    dp[nx][ny] -= 1
                    q.append((nx, ny))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys


def _i(): return int(sys.stdin.readline().strip())


def _ia(): return map(int, sys.stdin.readline().strip().split())


def update(n, cost, flag, idx, ci):
    # left
    if idx % n != 0:
        idx_ = idx - 1
        if cost[idx_] > ci:
            cost[idx_] = ci
            update(n, cost, flag, idx_, ci+flag[idx_])

    # right
    idx_ = idx + 1
    if idx_ % n != 0:
        if cost[idx_] > ci:
            cost[idx_] = ci
            update(n, cost, flag, idx_, ci+flag[idx_])

    # front
    idx_ = idx - n
    if idx_ >= 0:
        if cost[idx_] > ci:
            cost[idx_] = ci
            update(n, cost, flag, idx_, ci+flag[idx_])

    # back
    idx_ = idx + n
    if idx_ // n < n:
        if cost[idx_] > ci:
            cost[idx_] = ci
            update(n, cost, flag, idx_, ci+flag[idx_])


def main():
    n = _i()
    p = list(map(lambda x: int(x)-1, _ia()))
    cost = [min(i//n, i % n, n-1-(i % n), n-1-i//n) for i in range(n**2)]

    flag = [1] * n**2
    tot = 0
    for pi in p:
        flag[pi] = 0
        ci = cost[pi]
        tot += ci
        update(n, cost, flag, pi, ci)

    return tot


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

Submission status: Runtime Error

Solution code:
def N(): return int(input())
def NM():return map(int,input().split())
def L():return list(NM())
def LN(n):return [N() for i in range(n)]
def LL(n):return [L() for i in range(n)]
n=N()
p=L()
ans=[[0]*(n+1) for i in range(n+1)]
for i in range(1,n+1):
    for j in range(1,n+1):
        ans[i][j]=min(i-1,j-1,n-i,n-j)
c=[[1]*(n+1) for i in range(n+1)]
def f(x,y):
    for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
        if 1<=x+i<=n and 1<=y+j<=n:
            if ans[x][y]+c[x][y]<ans[x+i][y+j]:
                ans[x+i][y+j]-=1
                f(x+i,y+j)
t=0
for i in p:
    y=i%n
    if y==0:
        y=n
    x=(i+n-1)//n
    c[x][y]=0
    t+=ans[x][y]
    f(x,y)
print(t)

Submission status: Runtime Error

Solution code:
a