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:
from random import shuffle
N = int(input())
P = [int(c)-1 for c in input().split()]
#shuffle(P)
import numba
import numpy as np
#N = int(input())
#P = [int(c)-1 for c in input().split()]
# Mat = [[min(y, N-1-y, x, N-1-x) for y in range(N)] for x in range(N)]
# Mat = np.array(Mat)
@numba.njit()
def proc(N, P):
    ans = 0
    Removed = np.zeros((N, N), dtype=np.int32)
    closed = np.zeros((N,N), dtype=np.int32)
    Mat = np.zeros((N, N), dtype=np.int32)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

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

Submission status: Wrong Answer

Solution code:
import numpy as np
import collections

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

point_array = np.empty((N+2,N+2), dtype = int)

for i in range(N+2):
    for j in range(N+2):
        point_array[i][j] = min(i-1, j-1, N+2-i-2, N+2-j-2)
        if(point_array[i][j] == -1):
            point_array[i][j] = 0

#print(point_array)

calcDeque = collections.deque()
for P in Plist:
    calcDeque.append(P)

ans = 0
while len(calcDeque) != 0:
    toridashi = calcDeque.popleft()

    i = (toridashi) // N 
    j = (toridashi) % N
#    print(i,j)
    ans += point_array[i][j]
    if(point_array[i][j-1] > point_array[i][j]):
        point_array[i][j-1] = min(point_array[i][j+1], point_array[i+1][j], point_array[i-1][j]) +1
        calcDeque.appendleft(i * N + j - 1)

    if(point_array[i-1][j] > point_array[i][j]):
        point_array[i-1][j] = min(point_array[i][j+1], point_array[i+1][j], point_array[i][j-1]) +1
        calcDeque.appendleft((i-1) * N + j)

    if(point_array[i+1][j] > point_array[i][j]):
        point_array[i+1][j] = min(point_array[i][j+1], point_array[i][j-1], point_array[i-1][j]) +1
        calcDeque.appendleft((i+1) * N + j)

    if(point_array[i][j+1] > point_array[i][j]):
        point_array[i][j+1] = min(point_array[i][j-1], point_array[i+1][j], point_array[i-1][j]) +1
        calcDeque.appendleft(i * N + j)

    point_array[i][j] = 0
#    print(point_array)
#    print(ans)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import copy
n = int(input())
order = tuple(map(lambda x:int(x)-1, input().split()))

def bfs(i_y, i_x):
    tmp_chairs = copy.deepcopy(chairs)
    queue = deque()
    start = (i_y, i_x, 0)
    queue.append(start)
    # res = []
    res = 600
    while queue:
        y, x, unlike = queue.popleft()
        flag = False
        for i in range(4):
            tmp_y = y + dy[i]
            tmp_x = x + dx[i]
            if tmp_x >= n or tmp_x < 0 or tmp_y >= n or tmp_y < 0:
                chairs[i_y][i_x] = -1
                # if res >= unlike:
                #     return unlike
                res = min(res, unlike)
                # res.append(unlike)
                flag = True
                # return unlike
            elif tmp_chairs[tmp_y][tmp_x] == -1:
                tmp_chairs[y][x] = -2
                queue.append((tmp_y, tmp_x, unlike))
                # flag = True
            # else:
            #     if tmp_chairs[tmp_y][tmp_x] != -2:
            #         if tmp_y >= n-((n//2)-1) or tmp_y < (n//2)-1 or tmp_x >= n-((n//2)-1) or tmp_x < (n//2)-1:
            #             tmp_chairs[y][x] = -2
            #             queue.append((tmp_y, tmp_x, unlike+1))
            #             flag = True
        if not flag:
            for i in range(4):
                tmp_y = y + dy[i]
                tmp_x = x + dx[i]
                if tmp_chairs[tmp_y][tmp_x] != -2:
                    if tmp_y >= n-((n//2)-1) or tmp_y < (n//2)-1 or tmp_x >= n-((n//2)-1) or tmp_x < (n//2)-1:
                        tmp_chairs[y][x] = -2
                        queue.append((tmp_y, tmp_x, unlike+1))
    # return min(res)
    return res
# 座席作成
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
ans = 0
chairs = [[0] * n for _ in range(n)]
for i in range(n):
    for i_, j in enumerate(range(i*n, i*n+n)):
        chairs[i][i_] = j

for num in order:
    cnt = 0
    i_y, i_x = num//n, num%n
    ans += bfs(i_y, i_x)
print(ans)

Submission status: Wrong Answer

Solution code:
import os

import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


# MOD = 998244353


def test():
    ans_hist = [INF] * (N ** 2)

    ans = 0
    dist = [INF] * (N ** 2)
    for i, p in enumerate(P):
        p -= 1
        ph, pw = p // N, p % N
        d = min(ph, pw, N - ph - 1, N - pw - 1)

        j = i - 1
        while j >= 0:
            q = P[j] - 1
            qh, qw = q // N, q % N
            d = min(d, dist[q] + abs(ph - qh) + abs(pw - qw) - 1)
            j -= 1

        dist[p] = d
        ans_hist[p] = d

        j = i - 1
        while j >= 0:
            q = P[j] - 1
            qh, qw = q // N, q % N
            dist[q] = min(dist[q], dist[p] + abs(ph - qh) + abs(pw - qw) - 1)
            j -= 1

        ans += d
        # print(p, dist)
    print(ans)
    # print(dist)
    # print(np.array(ans_hist, dtype=int).reshape(N, N))
    return ans


N = int(sys.stdin.buffer.readline())
P = list(map(int, sys.stdin.buffer.readline().split()))

test()
exit()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**5)
N = int(input())
P = list(map(int, input().split()))

cost = [[N]*N for i in range(N)]

for i in range(N):
    cost[i][0] = 0
    cost[i][-1] = 0
    cost[0][i] = 0
    cost[-1][i] = 0

for i in range(1, N-1):
    for j in range(1, N-1):
        cost[i][j] = min(cost[i+1][j], cost[i-1][j],
                         cost[i][j+1], cost[i][j-1]) + 1

s = set()


def update(i, j):
    if i > 0:
        if cost[i][j]+1 == cost[i-1][j]:
            if (i-1, j) in s:
                cost[i-1][j] -= 1
                update(i-1, j)

            else:
                update(i-1, j)
                cost[i-1][j] -= 1
    if i < N-1:
        if cost[i][j]+1 == cost[i+1][j]:
            if (i+1, j) in s:
                cost[i+1][j] -= 1
                update(i+1, j)
            else:
                update(i+1, j)
                cost[i+1][j] -= 1
    if j > 0:
        if cost[i][j]+1 == cost[i][j-1]:
            if (i, j-1) in s:
                cost[i][j-1] -= 1
                update(i, j-1)
            else:
                update(i, j-1)
                cost[i][j-1] -= 1
    if j < N-1:
        if cost[i][j]+1 == cost[i][j+1]:
            if (i, j+1) in s:
                cost[i][j+1] -= 1
                update(i, j+1)
            else:
                update(i, j+1)
                cost[i][j+1] -= 1


ans = 0

for x in P:
    i = (x - 1) // N
    j = (x-1) % N
    ans += cost[i][j]
    s.add((i, j))
    # if cost[i][j]:
    #     print(x)
    #     print(*cost, sep='\n')
    #     print(ans)

    update(i, j)


print(ans)

Submission status: Wrong Answer

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,'',set(),0))
    # print('aa',i+1,c)
        
    
print(c)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


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

    bit = Bit(N)
    for i in range(1, N+1):
        bit.add(i, 1)

    rows = [Bit(N) for i in range(N)]
    rr = [N]*N
    cols = [Bit(N) for i in range(N)]
    cc = [N]*N
    for r in rows:
        r.tree = bit.tree.copy()
    for c in cols:
        c.tree = bit.tree.copy()

    ans = 0
    for p in P:
        # pの行番号、列番号
        r, c = divmod(p, N)
        # rowで抜ける場合
        t1 = rows[r].sum(c+1)-1          # 1-index
        t2 = rr[r]-t1-1
        t3 = cols[c].sum(r+1)-1          # 1-index
        t4 = cc[c]-t3-1
        tt = min(t1, t2, t3, t4)
        # print(p+1, t1, t2, t3, t4, "=>", tt)
        ans += tt
        rows[r].add(c+1, -1)
        cols[c].add(r+1, -1)
        rr[r] -= 1
        cc[c] -= 1
    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import math,bisect
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
  
n = int(readline())
a = [int(i) for i in readline().split()]
chk_y = [[0] for i in range(n)]
chk_t = [[0] for i in range(n)]
ans = 0
a = a[::-1]
    
for j in range(n*n):
  c = a[j]
  Y = math.ceil(c/n)
  T = c%n
  
  bisect.insort(chk_y[Y-1],c)
  bisect.insort(chk_t[T-1],c)
  
  if T > 1 and 1 < Y < n:
    if chk_y[Y-1][1] < c < chk_y[Y-1][-1] and chk_t[T-1][1] < c < chk_t[T-1][-1]:
      g = bisect.bisect_left(chk_y[Y-1],c)
      w = bisect.bisect_left(chk_t[T-1],c)
      ans += min(len(chk_y[Y-1])-g-1,g-1,len(chk_t[T-1])-w-1,w-1)
      #print(c,ans)

print(ans)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    __slots__ = ["_size", "_first_idx", "_parents", "_cost"]

    def __init__(self, size: int, N: int, first_index: int = 0) -> None:
        self._size = size
        self._first_idx = first_index
        self._parents = [-1] * (size + first_index)

        cost = [0] * (N * N)
        for r in range(N):
            dr = min(r, N - 1 - r)
            for c in range(N):
                dc = min(c, N - 1 - c)
                cost[r * N + c] = min(dr, dc)
        self._cost = cost

    def find(self, x: int) -> int:
        """Find the group (root) of vertex x"""
        if self._parents[x] < 0:
            return x
        self._parents[x] = self.find(self._parents[x])
        return self._parents[x]

    def is_same(self, x: int, y: int) -> bool:
        """Return whether two vertices x and y are in the same group or not."""
        return self.find(x) == self.find(y)

    def unite(self, x: int, y: int) -> None:
        """Unite two groups of vertices x and y."""
        c = min(self._cost[x], self._cost[y])
        x, y = self.find(x), self.find(y)
        if x == y:
            self._cost[x] = min(self._cost[x], c)
            return

        if self._parents[x] > self._parents[y]:
            x, y = y, x
        self._parents[x] += self._parents[y]
        self._parents[y] = x
        self._cost[x] = min(self._cost[x], self._cost[y], c)

    def get_size(self, x: int) -> int:
        """Get the size of the group vertex x belongs"""
        return -self._parents[self.find(x)]

    def get_cost(self, x: int) -> int:
        x = self.find(x)
        return self._cost[x]

    def set_cost(self, x: int, val: int):
        x = self.find(x)
        self._cost[x] = min(self._cost[x], val)


def main():
    N = int(input())
    *p, = (int(x) - 1 for x in input().split())

    g = [[set() for _ in range(N)] for _ in range(N)]
    for r in range(N):
        for c in range(N):
            if r > 0:
                g[r][c].add((r - 1, c))
            if c > 0:
                g[r][c].add((r, c - 1))
            if r < N - 1:
                g[r][c].add((r + 1, c))
            if c < N - 1:
                g[r][c].add((r, c + 1))

    uf = UnionFind(N * N, N)

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

    ans = 0
    for pi in p:
        r, c = divmod(pi, N)

        t = uf.get_cost(pi)
        for nr, nc in g[r][c]:
            if uf.is_same(nr * N + nc, pi):
                continue
            else:
                t = min(t, uf.get_cost(nr * N + nc) + (0 if ex[nr][nc] else 1))
        ans += t

        ex[r][c] = 1
        for nr, nc in g[r][c]:
            if ex[nr][nc]:
                uf.unite(nr * N + nc, pi)

    print(ans)


if __name__ == '__main__':
    main()

# import sys
# input = sys.stdin.readline
#
# sys.setrecursionlimit(10 ** 7)
#
# (int(x)-1 for x in input().split())
# rstrip()
#
# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok

Submission status: Wrong Answer

Solution code:
import sys

import heapq

readline = sys.stdin.buffer.readline


def start_point(P):
    j, i = divmod(P, N)
    return i, j


def bfs(start, ch, reached):
    tests = ((1, 0), (-1, 0), (0, 1), (0, -1))
    queue = []
    moves = 0
    heapq.heappush(queue, (start[0], start[1], moves))
    ans = []

    while queue:
        queue_next = []

        for _ in range(len(queue)):
            x, y, o_move = heapq.heappop(queue)
            for dx, dy in tests:
                tx, ty = x + dx, y + dy
                if tx < N and 0 <= tx and ty < N and 0 <= ty:
                    if reached[tx][ty] is False:
                        if ch[tx][ty] is False:
                            reached[tx][ty] = o_move
                            heapq.heappush(queue_next, (tx, ty, o_move))
                        else:
                            reached[tx][ty] = o_move + 1
                            heapq.heappush(queue_next, (tx, ty, o_move + 1))

                else:
                    ans.append(o_move)

        queue = queue_next

    return min(ans)


# 嫌われる人数 = min(通路までの距離, すでに人がいない席までの距離)
# すでに人がいない席までの距離はwfs

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

# O始まりに変換
P = list(map(lambda x: x - 1, P))

cnt = 0

# True: 人がいる
ch = [[True for _ in range(N)] for _ in range(N)]

# 最初の一人は通路までの距離
start = start_point(P[0])
cnt += min(start)
ch[start[0]][start[1]] = False

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

for p in P[1:]:
    start = start_point(p)

    # 通路までの距離
    m0 = min(start[0], start[1], abs(N - start[0] - 1), abs(N - start[1] - 1))

    if m0 != 0:
        # 人がいない席までの距離
        reached = [[False for _ in range(N)] for _ in range(N)]
        m1 = bfs(start, ch, reached)
    else:
        m1 = 0

    ch[start[0]][start[1]] = False
    cnt += min(m0, m1)

print(cnt)

Submission status: Wrong Answer

Solution code:
import sys

import heapq

readline = sys.stdin.buffer.readline


def start_point(P):
    j, i = divmod(P, N)
    return i, j


def bfs(start, ch, reached):
    tests = ((1, 0), (-1, 0), (0, 1), (0, -1))
    queue = []
    moves = 0
    heapq.heappush(queue, (start[0], start[1], moves))
    ans = []

    while queue:
        queue_next = []

        for _ in range(len(queue)):
            x, y, o_move = heapq.heappop(queue)
            for dx, dy in tests:
                tx, ty = x + dx, y + dy
                if tx < N and 0 <= tx and ty < N and 0 <= ty:
                    if reached[tx][ty] is False:
                        if ch[tx][ty] is False:
                            reached[tx][ty] = o_move
                            heapq.heappush(queue_next, (tx, ty, o_move))
                        else:
                            reached[tx][ty] = o_move + 1
                            heapq.heappush(queue_next, (tx, ty, o_move + 1))

                else:
                    ans.append(o_move)

        queue = queue_next

    return min(ans)


# 嫌われる人数 = min(通路までの距離, すでに人がいない席までの距離)
# すでに人がいない席までの距離はwfs

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

# O始まりに変換
P = list(map(lambda x: x - 1, P))

cnt = 0

# True: 人がいる
ch = [[True for _ in range(N)] for _ in range(N)]

# 最初の一人は通路までの距離
start = start_point(P[0])
cnt += min(start)
ch[start[0]][start[1]] = False

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

for p in P[1:]:
    start = start_point(p)

    # 通路までの距離
    m0 = min(start[0], start[1], abs(N - start[0] - 1), abs(N - start[1] - 1))

    if m0 != 0:
        # 人がいない席までの距離
        reached = [[False for _ in range(N)] for _ in range(N)]
        m1 = bfs(start, ch, reached)
    else:
        m1 = 0

    ch[start[0]][start[1]] = False
    cnt += min(m0, m1)

print(cnt)

Submission status: Wrong Answer

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

N = int(readline())
P = np.array(list(map(int, readline().split())))

data = np.ones((N,N))
ans = 0

# 座ってる場所のindex判定
def seat_index(seat_num):
  div,mod = divmod(seat_num, N)
  if mod % N == 0:
    col = div-1
    row = N-1
  else:
    col = div
    row = mod-1
  return [col,row]

# 嫌う人数判定
def check(col, row):
  data[col][row] = 0
  if col == 0 or col == N or row == 0 or row == N or np.sum(data[col,:row]) == 0 or np.sum(data[col,:row]) == 0 or np.sum(data[:col,row]) == 0 or np.sum(data[col+1:,row]) == 0:
    return 0
  else:
    return np.min(np.array([np.sum(data[col,:row]),np.sum(data[col,row+1:])
                       ,np.sum(data[:col,row]),np.sum(data[col+1:,row])]))


for i in range(len(P)):
  seat_num = P[i]
  col,row = seat_index(seat_num)
  ans += int(check(col,row))


print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
import itertools
import collections
import numpy as np

rl = sys.stdin.readline
n = int(rl())
dp = np.full((n, n), 500)
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def m(x, y):
    global mi
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if nx < 0 or ny < 0 or nx >= n or ny >= n or dp[nx][ny] == 0:
            dp[x][y] = 0
            break
        else:
            if dp[nx][ny] == 500:
                if x >= n/2:
                    tempx = n-x-1
                    if y >= n/2:
                        tempy = n-y-1
                        if tempx > tempy:
                            temp = tempy
                        else:
                            temp = tempx
                    else:
                        tempy = y
                        if tempx > tempy:
                            temp = tempy
                        else:
                            temp = tempx
                else:
                    tempx = x
                    if y >= n/2:
                        tempy = n-y-1
                        if tempx > tempy:
                            temp = tempy
                        else:
                            temp = tempx
                    else:
                        tempy = y
                        if tempx > tempy:
                            temp = tempy
                        else:
                            temp = tempx
                if temp < mi:
                    mi = temp
            elif dp[x][y] != mi:
                m(nx, ny)
            elif dp[nx][ny] < mi:
                mi = dp[nx][ny]
            dp[x][y] = mi
for nu in list(map(int, rl().split())):
    x1 = (nu-1)%n
    y1 = (nu-1)//n
    mi = 500
    m(x1, y1)
print(sum(sum(dp))-(n-3))

Submission status: Wrong Answer

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

dp = [[1 + min(i, N - 1 - i, j, N - 1 - j) for j in range(N + 1)] for i in range(N + 1)]

presence = [[1 for j in range(N)] for i in range(N)]

ans = 0
for i in range(len(P)):
    P[i] -= 1
    x = P[i] // N
    y = P[i] % N
    ans += dp[x][y] - 1
    presence[x][y] = 0

    Q = [(x, y)]
    visited = set()
    while Q:
        x, y = Q.pop()
        visited.add((x, y))
        new_value = presence[x][y] + min(
            dp[x - 1][y], dp[x + 1][y], dp[x][y - 1], dp[x][y + 1]
        )
        if new_value != dp[x][y]:
            dp[x][y] = new_value
            if 1 <= x and (x - 1, y) not in visited:
                Q.append((x - 1, y))
            if x < N - 1 and (x + 1, y) not in visited:
                Q.append((x + 1, y))
            if 1 <= y and (x, y - 1) not in visited:
                Q.append((x, y - 1))
            if y < N - 1 and (x, y + 1) not in visited:
                Q.append((x, y + 1))

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

max_int = 1000000001  # 10^9+1
min_int = -max_int

n = int(sys.stdin.readline())
p = sys.stdin.readline().split()
d = [0] * len(p)

for move_number, pos in enumerate(p, 1):
    d[int(pos) - 1] = move_number

ans = 0
for x in range(n):
    for y in range(n):
        pos = y * n + x
        distances = []
        cntr = 0
        for i in range(x + 1, n):
            if d[pos] < d[y * n + i]:
                cntr += 1
        distances.append(cntr)
        if cntr == 0:
            continue
        # else:


        cntr = 0
        for i in range(x - 1, -1, -1):
            if d[pos] < d[y * n + i]:
                cntr += 1
        distances.append(cntr)
        if cntr == 0:
            continue

        cntr = 0
        for i in range(y + 1, n):
            if d[pos] < d[i * n + x]:
                cntr += 1
        distances.append(cntr)
        if cntr == 0:
            continue

        cntr = 0
        for i in range(y - 1, -1, -1):
            if d[pos] < d[i * n + x]:
                cntr += 1
        distances.append(cntr)
        if cntr == 0:
            continue

        ans += min(distances)

print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N = int(input())
    P = [int(i)-1 for i in input().split(' ')]
    seat = [[1 for j in range(N)] for i in range(N)]
    score = 0
    for i in range(len(P)):
        if P[i]//N%N== 0 or P[i]%N%N == 0:
            seat[P[i]//N][(P[i])%N] = 0
            continue
        left = sum(seat[P[i]//N][:P[i]%N])
        if left == 0:
            seat[P[i]//N][(P[i])%N] = 0
            continue
        right = sum(seat[P[i]//N][P[i]%N:])-1 if sum(seat[P[i]//N][P[i]%N:])-1>=0 else 0
        if right == 0:
            seat[P[i]//N][(P[i])%N] = 0
            continue
        top = 0
        j = P[i]//N-1
        while True:
            if j >= 0:
                top += seat[j][P[i]%N]
            else:
                break
            j -= 1
        if top == 0:
            seat[P[i]//N][(P[i])%N] = 0
            continue
        bottom = 0
        j = P[i]//N+1
        while True:
            if j < N:
                bottom += seat[j][P[i]%N]
            else:
                break
            j += 1
        if bottom == 0:
            seat[P[i]//N][(P[i])%N] = 0
            continue
        score_direction = [left, right, top, bottom]
        score += min(score_direction)
        seat[P[i]//N][(P[i])%N] = 0
    print(score)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np
N = int(input())
# = map(int, input().split())
P = list(map(int, input().split()))
# = [int(input()) for i in range(N)]
# = [list(map(int, input().split())) for i in range(N)]
seat = np.ones((N, N))
total = 0

for i in range(N**2):
    tate = (P[i]-1)//N
    yoko = (P[i]-1)%N
    if yoko == 0 or yoko == N-1 or tate == 0:
        seat[tate][yoko] = 0
    else:
        shortest = N
        count = 0
        for i in range(yoko):
            if seat[tate][i] == 1:
                count+=1
        if count < shortest:
            shortest = count
        count = 0
        for i in range(N-yoko):
            if seat[tate][N-1-i] == 1:
                count += 1
        if count < shortest:
            shortest = count
        count = 0
        for i in range(tate):
            if seat[i][yoko] == 1:
                count+=1
        if count < shortest:
            shortest = count
        count = 0
        for i in range(N-tate):
            if seat[N-1-i][yoko] == 1:
                count += 1
        if count < shortest:
            shortest = count
        total += shortest
        seat[tate][yoko] = 0

print(total)

Submission status: Wrong Answer

Solution code:
from sys import stdin

def checkans(N,arg,i):
    # 上をチェック
    uecount = 0
    bai = 1
    while (i + N * bai) < len(arg)-1:
        # print(i+N*bai)
        if arg[i+N*bai] != 0:
            uecount += 1
        bai += 1
    # 下をチェック
    shitacount = 0
    bai = 1
    while i - N * bai > 0:
        if arg[i - N * bai] != 0:
            shitacount += 1
        bai += 1
    # 右をチェック
    migicount = 0
    for a in range(i+1, N*(i//N+1)):
        if arg[a] != 0:
            migicount += 1
    # 左をチェック
    hidaricount = 0
    for a in range(N*(i//N),i):
        if arg[a] != 0:
            hidaricount += 1
    # print(f'uecount,shitacount,migicount,hidaricount {uecount} {shitacount} {migicount} {hidaricount}')
    return min(uecount, shitacount, migicount, hidaricount)

N = int(input())
P = list(map(int,stdin.readline().split()))
seki = [a+1 for a in range(N**2)]

ans = 0
for a,b in enumerate(P):
    ans += checkans(N,seki,b-1)
    seki[P[a]-1] = 0
    # print(f'ans = {ans}')
    # print(f'P = {seki}')

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
p = list(map(int, input().split()))
s = [[0]*n for _ in range(n)]

ans = 0
def edge(N, i):
    if i % N == 0 or i % N == 1:
        return 1
    elif i > 1 and i <N:
        return 1
    elif i > N**2-N+1 and i<N**2:
        return 1
    else:
        return 0
    
def check(n, s, r, c):
    b =  1
    if not r ==0: #縦↑
        for j in range(r):
            if s[j][c]==0:
                b = 0
        if b==1:return 1
        else:b=1
        
    if not r == n-1: #縦↓
        for j in range(r+1, n):
            if s[j][c]==0:
                b = 0
        if b==1:return 1
        else:b=1
        
    if not c == 0: #横←
        for j in range(c):
            if s[r][j]==0:
                b = 0
        if b==1:return 1
        else:b=1
        
    if not c == n-1: #縦↓
        for j in range(c+1, n):
            if s[r][j]==0:
                b = 0
        if b==1:return 1  
    return 0

from collections import deque
def mini(n, s, r, c):
    seen = [[0]*n for _ in range(n)]
    x = [1, 0, -1, 0]
    y = [0, 1, 0, -1]
    queue = deque([r, c])
    t = 10**100
    while queue:
        qr = queue.popleft()
        qc = queue.popleft()
        temp = min(qr, qc, n-qr-1, n-qc-1)
        t = min(t, temp)

        for i in range(4):
            if qr+x[i]>=0 and qr+x[i]<n and  qc+y[i]>=0 and qc+y[i]<n:
                if s[qr+x[i]][qc+y[i]] == 1 and seen[qr+x[i]][qc+y[i]]==0:
                    queue.append(qr+x[i])
                    queue.append(qc+y[i])
                    seen[qr+x[i]][qc+y[i]]=1
    return t

for i in p:
    if i % n ==0:
        r = i//n-1
        c = n-1
    else:
        r = i//n
        c = i%n-1
    if edge(n, i):
        s[r][c] = 1
        continue
    elif check(n, s, r, c):
        s[r][c] = 1
        continue
    else:
        s[r][c] = 1
        ans += mini(n, s, r, c)    
        
print(ans)