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: Wrong Answer

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(map(int, input().split()))
mod=1000000007

#+++++

#@jit
def gg(nn, x, y, n, is_sit, cc, av):
	q = deque()
	q.append(1000*x+y)
	while q:
		v = q.popleft()
		x,y = v//1000, v %1000
		nn[x][y] -= 1
		k = nn[x][y]
		cc[x][y]=av
		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 cc[x+dx][y+dy]==av:
				continue
			q.append((x+dx)*1000+ (y+dy))
			cc[x+dx][y+dy]=av
		#print('yyyyyy')
		#for l,ll in zip(nn,cc):
		#	print(l,ll)

def main():
	n = int(input())
	nn = [[(n+1)//2] * n for _ in range(n)]
	is_sit = [[1] * n for _ in range(n)]
	cc = [[0]*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 i, p in enumerate(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, cc, i)
		
	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: Wrong Answer

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


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

INF = 2**62-1


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


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


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


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


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


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

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


def mt(f):
    import time

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

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

    return wrap


class UnionFind():
    def __init__(self):
        self.__table = {}
        self.__size = defaultdict(lambda: 1)
        self.__rank = defaultdict(lambda: 1)

    def __root(self, x):
        if x not in self.__table:
            self.__table[x] = x
        elif x != self.__table[x]:
            self.__table[x] = self.__root(self.__table[x])
        return self.__table[x]
    def root(self, x):
        # print(self.__table)
        return self.__root(x)

    def same(self, x, y):
        return self.__root(x) == self.__root(y)

    def union(self, x, y):
        x = self.__root(x)
        y = self.__root(y)
        if x == y:
            return x

        if self.__rank[x] < self.__rank[y]:
            self.__table[x] = y
            self.__size[y] += self.__size[x]
        else:
            self.__table[y] = x
            self.__size[x] += self.__size[y]
            if self.__rank[x] == self.__rank[y]:
                self.__rank[x] += 1
        return self.__root(x)

    def size(self, x):
        return self.__size[self.__root(x)]

    def num_of_group(self):
        g = 0
        for k, v in self.__table.items():
            if k == v:
                g += 1
        return g



@mt
def slv(N, P):
    P = [p-1 for p in P]

    cd = {}
    for x in range(N):
        for y in range(N):
            cost = min(x, y, N-x-1, N-y-1)
            i = x*N + y
            cd[i] = cost
    done = set()
    ans = 0
    for p in P:
        x = p // N
        y = p % N
        ans += cd[p]
        s = [(x, y, cd[p])]
        done.add(p)
        while s:
            # print(s)
            x, y, c = s.pop()
            for i, j in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                if 0 <= x+i < N and 0 <= y+j < N:
                    k = (x+i)*N + (y+j)
                    o = -1 if k in done else 0
                    if c + o < cd[k]:
                        s.append((x+i, y+j, cd[k]))
                        cd[k] = min(cd[k], c+o)

        # print('----', p)
        # for i in range(N):
        #     print([cd[i*N+j] for j in range(N)])
    return ans


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


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

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

def bfs(src):
    from collections import deque

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

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

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

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

Submission status: Wrong Answer

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.int16)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1

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

    ans = 0

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

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

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

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

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

    return ans


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

# n = 500
# ppp = np.random.permutation(n * n).astype(np.int64)
# print(ppp)

print(solve(n, ppp))

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

Submission status: Wrong Answer

Solution code:
import collections
import itertools


def main():
    N = int(input())
    S = N + 2
    M = N * N
    cells = [[1] * (S) for _ in range(S)]
    costs = [[M] * S for _ in range(S)]
    total_cost = 0

    queue = collections.deque()

    for v in range(S - 1):
        costs[0][v] = 0
        costs[S - 1][v + 1] = 0
        costs[v + 1][0] = 0
        costs[v][S - 1] = 0

        cells[0][v] = 0
        cells[S - 1][v + 1] = 0
        cells[v + 1][0] = 0
        cells[v][S - 1] = 0

        queue.append((v, 0))
        queue.append((v + 1, S - 1))
        queue.append((0, v + 1))
        queue.append((S - 1, v))

    while len(queue) != 0:
        x, y = queue.popleft()
        c = costs[y][x]

        if x > 0 and costs[y][x - 1] == M:
            costs[y][x - 1] = c + 1
            queue.append((x - 1, y))

        if x < S - 1 and costs[y][x + 1] == M:
            costs[y][x + 1] = c + 1
            queue.append((x + 1, y))

        if y > 0 and costs[y - 1][x] == M:
            costs[y - 1][x] = c + 1
            queue.append((x, y - 1))

        if y < S - 1 and costs[y + 1][x] == M:
            costs[y + 1][x] = c + 1
            queue.append((x, y + 1))

    for i in map(int, input().split()):
        x, y = divmod(i - 1, N)
        x, y = x + 1, y + 1

        total_cost += costs[y][x] - 1
        cells[y][x] = 0

        queue = collections.deque()
        queue.append((x, y))

        while len(queue) != 0:
            x, y = queue.popleft()
            c = costs[y][x] + cells[y][x]

            for ax, ay in ((1, 0), (0, -1), (0, 1), (0, -1)):
                nx, ny = x + ax, y + ay

                if costs[ny][nx] > c:
                    costs[ny][nx] = c
                    queue.append((nx, ny))

    print(total_cost)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import collections
import itertools


def main():
    N = int(input())
    S = N + 2
    M = N * N
    cells = [[1] * (S) for _ in range(S)]
    costs = [[M] * S for _ in range(S)]
    total_cost = 0

    queue = collections.deque()

    for v in range(S - 1):
        costs[0][v] = 0
        costs[S - 1][v + 1] = 0
        costs[v + 1][0] = 0
        costs[v][S - 1] = 0

        cells[0][v] = 0
        cells[S - 1][v + 1] = 0
        cells[v + 1][0] = 0
        cells[v][S - 1] = 0

        queue.append((v, 0))
        queue.append((v + 1, S - 1))
        queue.append((0, v + 1))
        queue.append((S - 1, v))

    while len(queue) != 0:
        x, y = queue.popleft()
        c = costs[y][x]

        if x > 0 and costs[y][x - 1] == M:
            costs[y][x - 1] = c + 1
            queue.append((x - 1, y))

        if x < S - 1 and costs[y][x + 1] == M:
            costs[y][x + 1] = c + 1
            queue.append((x + 1, y))

        if y > 0 and costs[y - 1][x] == M:
            costs[y - 1][x] = c + 1
            queue.append((x, y - 1))

        if y < S - 1 and costs[y + 1][x] == M:
            costs[y + 1][x] = c + 1
            queue.append((x, y + 1))

    for i in map(int, input().split()):
        x, y = divmod(i - 1, N)
        x, y = x + 1, y + 1
        total_cost += costs[y][x] - 1

        costs[y][x] -= 1
        cells[y][x] = 0
        queue = collections.deque()
        queue.append((x, y))

        while len(queue) != 0:
            x, y = queue.popleft()

            for ax, ay in ((1, 0), (0, -1), (0, 1), (0, -1)):
                nx, ny = x + ax, y + ay
                c = costs[y][x] + cells[ny][nx]

                if costs[ny][nx] > c:
                    costs[ny][nx] = c
                    queue.append((nx, ny))

    print(total_cost)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import collections
import itertools


def main():
    N = int(input())
    S = N + 2
    M = N * N
    cells = [[1] * (S) for _ in range(S)]
    costs = [[M] * S for _ in range(S)]
    total_cost = 0

    queue = collections.deque()

    for v in range(S - 1):
        costs[0][v] = 0
        costs[S - 1][v + 1] = 0
        costs[v + 1][0] = 0
        costs[v][S - 1] = 0

        cells[0][v] = 0
        cells[S - 1][v + 1] = 0
        cells[v + 1][0] = 0
        cells[v][S - 1] = 0

        queue.append((v, 0))
        queue.append((v + 1, S - 1))
        queue.append((0, v + 1))
        queue.append((S - 1, v))

    while len(queue) != 0:
        x, y = queue.popleft()
        c = costs[y][x]

        if x > 0 and costs[y][x - 1] == M:
            costs[y][x - 1] = c + 1
            queue.append((x - 1, y))

        if x < S - 1 and costs[y][x + 1] == M:
            costs[y][x + 1] = c + 1
            queue.append((x + 1, y))

        if y > 0 and costs[y - 1][x] == M:
            costs[y - 1][x] = c + 1
            queue.append((x, y - 1))

        if y < S - 1 and costs[y + 1][x] == M:
            costs[y + 1][x] = c + 1
            queue.append((x, y + 1))

    for i in map(int, input().split()):
        x, y = divmod(i - 1, N)
        x, y = x + 1, y + 1
        total_cost += costs[y][x] - 1

        cells[y][x] = 0
        queue = collections.deque()
        queue.append((x, y))

        while len(queue) != 0:
            x, y = queue.popleft()
            c = costs[y][x] + cells[y][x]

            for ax, ay in ((1, 0), (0, -1), (0, 1), (0, -1)):
                nx, ny = x + ax, y + ay

                if costs[ny][nx] > c:
                    costs[ny][nx] = c
                    queue.append((nx, ny))

    print(total_cost)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
ha = 2
while ha<2*n:
    ha=ha*2
N= int(ha/2)
ha -= 1
# print(ha)
def update(x,y,w,h,num):
    x += w-1 
    y += h-1 
    f[y][x] = num
    # print("x1",x)
    # 層をのぼりながら値を更新
    tmp_x = x
    while x > 0:
        x = (x-1)// 2 # 1つ上の層のインデックス(完全二分木における親)
        # print("x",x)
        # 下の層2つの和を代入(完全二分木における子同士の和)
        f[y][x] = f[y][x*2+1] + f[y][x*2+2]
    while y > 0:
        y = (y-1)// 2 # 1つ上の層のインデックス(完全二分木における親)
        # print("x",x)
        # 下の層2つの和を代入(完全二分木における子同士の和)
        f[y][tmp_x] = f[y*2+1][tmp_x] + f[y*2+2][tmp_x]

def query_yoko(l, r, y,k=0, L=0, R=None):#y固定
    # Rの初期化
    # print(l,r)

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

    # 区間[L,R)が区間[l,r)に完全に収まっていればその値を返す
    if l <= L and R <= r:
        return f[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 f[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(f)):
        print(f[i])

f = [[0 for _ in range(ha)]for _ in range(ha)]

for i in range(n*n):#構築
    # print("------")
    y ,x = divmod(i,n)
    # print("koutiku",i,x,y)
    update(x,y,N,N,1)
    
    # print(i)
    # show()
a = list(map(int,input().split()))
ans = 0
# print(a)
for i in range(n*n):
    y ,x = divmod(a[i]-1,n)
    update(x,y,N,N,0)
    q1 = query_yoko(0,x,y+N-1)
    q2 = query_yoko(x,N,y+N-1)
    q3 = query_tate(0,y,x+N-1)
    q4 = query_tate(y,N,x+N-1)
    # 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)

Submission status: Wrong Answer

Solution code:
import math
from collections import deque
import numpy as np
import sys
sys.setrecursionlimit(1000000)

n = int(input())
p = map(lambda x: int(x) - 1, input().split())
cost = np.zeros((n, n))
q = deque(p)
dir = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(math.ceil(n / 2)):
    cost[i:-i, i] = i
    cost[i:-i, -(i + 1)] = i
    cost[i, i:-i] = i
    cost[-(i + 1), i:-i] = i
ans = 0
used = np.zeros((n, n))


def attached(x, y, new_cost):
    for i, j in dir:
        if 0 <= x + i < n and 0 <= y + j < n and not(used[x + i, y + j]):
            if cost[x + i, y + j] > new_cost:
                cost[x + i, y + j] = new_cost
        elif 0 <= x + i < n and 0 <= y + j < n and used[x + i, y + j]:
            attached(x + 1, y + 1, new_cost)


while q:
    pe = q.popleft()
    x = pe // n
    y = pe % n
    ans += cost[x, y]
    used[x, y] = 1
    attached(x, y, cost[x, y])

    print(cost, pe, ans)
print(int(ans))

Submission status: Wrong Answer

Solution code:
import sys, math
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7

from pprint import pprint

N = ri()
P = rl()

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

def init(xflip, yflip):
    for i in range(1, math.ceil(N/2)):
        for j in range(1, math.ceil(N/2)):
            ni, nj = i, j
            di, dj = -1, -1
            if xflip:
                nj = N-1-j
                dj = 1
            if yflip:
                ni = N-1-i
                di = 1
            dp[ni][nj] = min(dp[ni+di][nj],dp[ni][nj+dj])+1

for xflip, yflip in [(0,0),(1,0),(0,1),(1,1)]:
    init(xflip, yflip)

def get_ij(p):
    n = p-1
    i = n // N
    j = n % N
    return i, j

import collections
outs = {}
def update(i, j):
    outs[(i,j)] = 1
    queue = collections.deque()
    queue.append((i,j))
    while queue:
        i, j = queue.popleft()
        for di, dj in [(1,0),(-1,0),(0,1),(0,-1)]:
            ni, nj = i+di, j+dj
            if not (0 <= ni < N and 0 <= nj < N):
                continue
            if dp[ni][nj] > dp[i][j]:
                dp[ni][nj] = dp[i][j]
                if (ni,nj) in outs:
                    queue.append((ni,nj))

ans = 0
for p in P:
    n = p-1
    i, j = get_ij(p)
    ans += dp[i][j]
    update(i,j)
    #pprint(dp)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
#import numpy

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

def dfsr(i, j, cnt):
    global seet, N
    if j+1 < N:
        if seet[i][j+1] == -1:
            dfsr(i, j+1, cnt)
        else:
            if seet[i][j+1] > cnt:
                seet[i][j+1] = cnt
                dfs(i, j+1, cnt+1)

def dfsl(i, j, cnt):
    global seet, N
    if j-1 >= 0:
        if seet[i][j-1] == -1:
            dfsr(i, j-1, cnt)
        else:
            if seet[i][j-1] > cnt:
                seet[i][j-1] = cnt
                dfs(i, j-1, cnt+1)

def dfsu(i, j, cnt):
    global seet, N
    if i-1 >= 0:
        if seet[i-1][j] == -1:
            dfsr(i-1, j, cnt)
        else:
            if seet[i-1][j] > cnt:
                seet[i-1][j] = cnt
                dfs(i-1, j, cnt+1)

def dfsd(i, j, cnt):
    global seet, N
    if i+1 < N:
        if seet[i+1][j] == -1:
            dfsr(i+1, j, cnt)
        else:
            if seet[i+1][j] > cnt:
                seet[i+1][j] = cnt
                dfs(i+1, j, cnt+1)

def dfs(i, j, cnt):
    global seet, N
    if i+1 < N:
        if seet[i+1][j] > cnt+1:
            seet[i+1][j] = cnt+1
            dfs(i+1, j, cnt+1)
    if i-1 >= 0:
        if seet[i-1][j] > cnt+1:
            seet[i-1][j] = cnt+1
            dfs(i-1, j, cnt+1)
    if j+1 < N:
        if seet[i][j+1] > cnt+1:
            seet[i][j+1] = cnt+1
            dfs(i, j+1, cnt+1)
    if j-1 >= 0:
        if seet[i][j-1] > cnt+1:
            seet[i][j-1] = cnt+1
            dfs(i, j-1, cnt+1)

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

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

    #nseet = numpy.array(seet)

    ans = 0
    for p in P:
        i, j = (p-1)//N, (p-1)%N
        seetij = seet[i][j]
        ans += seetij
        if i+1 < N:
            if seet[i+1][j] == -1:
                dfsd(i+1, j, seetij)
            if seet[i+1][j] > seetij:
                seet[i+1][j] = seetij
                dfs(i+1, j, seetij)
        if i-1 >= 0:
            if seet[i-1][j] == -1:
                dfsu(i-1, j, seetij)
            if seet[i-1][j] > seetij:
                seet[i-1][j] = seetij
                dfs(i-1, j, seetij)
        if j+1 < N:
            if seet[i][j+1] == -1:
                dfsr(i, j+1, seetij)
            if seet[i][j+1] > seetij:
                seet[i][j+1] = seetij
                dfs(i, j+1, seetij)
        if j-1 >= 0:
            if seet[i][j-1] == -1:
                dfsl(i, j-1, seetij)
            if seet[i][j-1] > seetij:
                seet[i][j-1] = seetij
                dfs(i, j-1, seetij)
        seet[i][j] = -1

    #print(nseet)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
mod = 1000000007
m = [(0, 1), (1, 0), (-1, 0), (0, -1)]
inf = float('INF')

#solve
def solve():
    n = II()
    p = LI()
    dp = [min(i, j, n - i - 1, n - j - 1) for i in range(n) for j in range(n)]
    c = [1 for i in range(n) for j in range(n)]
    d = defaultdict(tuple)
    for i in range(-1, n + 1):
        for j in range(-1, n + 1):
            d[i * n + j] = (i, j)
    q = [0] * (n ** 2)
    ans = 0
    for pi in p:
        pi -= 1
        ans += dp[pi]
        c[pi] = 0
        q[0] = pi
        p = 0
        l = 1
        while p != l:
            yx = q[p]
            p += 1
            score = dp[yx] + c[yx]
            y, x = d[yx]
            if 0 < y < n - 1:
                if 0 < x < n - 1:
                    myx = yx + n
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx - n
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx - 1
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx + 1
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                else:
                    if 0 == x:
                        myx = yx + 1
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
                    elif n - 1 == x:
                        myx = yx - 1
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
            else:
                if y == 0:
                    if 0 < x < n - 1:
                        myx = yx + n
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
                elif y == n - 1:
                    if 0 < x < n - 1:
                        myx = yx - n
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
    print(ans)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
mod = 1000000007
m = [(0, 1), (1, 0), (-1, 0), (0, -1)]
inf = float('INF')

#solve
def solve():
    n = II()
    p = LI()
    dp = [min(i, j, n - i - 1, n - j - 1) for i in range(n) for j in range(n)]
    c = [1 for i in range(n) for j in range(n)]
    d = defaultdict(tuple)
    for i in range(-1, n + 1):
        for j in range(-1, n + 1):
            d[i * n + j] = (i, j)
    q = [0] * (n ** 2)
    ans = 0
    for pi in p:
        pi -= 1
        ans += dp[pi]
        c[pi] = 0
        q[0] = pi
        p = 0
        l = 1
        while p != l:
            yx = q[p]
            p += 1
            score = dp[yx] + c[yx]
            y, x = d[yx]
            if 0 < y < n - 1:
                if 0 < x < n - 1:
                    myx = yx + n
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx - n
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx - 1
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx + 1
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                else:
                    if 0 == x:
                        myx = yx + 1
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
                    else:
                        myx = yx - 1
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
            else:
                if y == 0:
                    if 0 < x < n - 1:
                        myx = yx + n
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
                else:
                    if 0 < x < n - 1:
                        myx = yx - n
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
    print(ans)
    return


#main
if __name__ == '__main__':
    solve()