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
input=sys.stdin.readline
import heapq
def dijkstra(s,graph,n):
    dist=[float("inf") for i in range(n+1)]
    dist[s]=0
    pq=[]
    heapq.heapify(pq)
    heapq.heappush(pq,(0,s))
    while pq:
        mini_dis,node=heapq.heappop(pq)
        if dist[node]<mini_dis: continue
        for w,point in graph[node]:
            if dist[point]<w:continue
            newlen=dist[node]+w
            if newlen<dist[point]:
                heapq.heappush(pq,(newlen,point))
                dist[point]=newlen
    return dist
def main():
    N=int(input())
    que=list(map(int,input().split()))
    from collections import defaultdict
    dif=[1,-1,N,-N]
    graph=[[] for i in range(N**2+1)]
    for i in range(N):
        for j in range(N):
            node=N*i+j+1
            for num in dif:
                if 1<=node+num<=N**2:
                    graph[node].append((1,node+num))
                    graph[node+num].append((1,node))
    ans=0
    for i in range(N):
        graph[0].append((0,i+1))
        graph[i+1].append((0,0))
        graph[0].append((0,N*(N-1)+i+1))
        graph[N*(N-1)+i+1].append((0,0))
        
    vanished=[False for i in range(N**2+1)]
    
    for i in range(N):
        graph[0].append((0,i*N+1))
        graph[i*N+1].append((0,0))
        graph[0].append((0,i*N+N))
        graph[i*N+N].append((0,0))
    for some in range(1):
        some=que[some]
        ans+=dijkstra(some,graph,N**2)[0]
        vanished[some]=True
        for num in dif:
            if 1<=num+some<=N**2:
                if vanished[num+some]:
                    graph[some].append((0,num+some))
                    graph[num+some].append((0,some))
                else:
                    graph[num+some].append((0,some))
    print(ans)    
if __name__=="__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

n, *ppp = map(int, sys.stdin.buffer.read().split())

n2 = n + 2
row_base0 = list(range(n))
row_base1 = [-1] + row_base0 + [-1]
row_base0.reverse()
row_base2 = [-1] + row_base0 + [-1]
row_base = [min(a, b) for a, b in zip(row_base1, row_base2)]

seats = [-1] * n2
for i in range(n):
    ud = min(i, n - 1 - i)
    seats.extend(min(a, ud) for a in row_base)
seats.extend([-1] * n2)

is_seated = [False] * n2
is_seated.extend(([False] + [True] * n + [False]) * n)
is_seated.extend([False] * n2)


def pg(aaa):
    for i in range(0, n2 ** 2, n2):
        print(aaa[i:i + n2])
    print()


ans = 0
MOVE = (-n2, -1, 1, n2)
q = deque()
popl = q.popleft
appl = q.appendleft
appr = q.append
clrq = q.clear

# debug
exit()

for p in ppp:
    i, j = divmod(p - 1, n)
    i = (i + 1) * n2 + j + 1
    res = seats[i]
    ans += res
    is_seated[i] = False

    appr((res, i))
    updated = set()

    while q:
        val, j = popl()
        if j in updated:
            continue
        updated.add(j)
        seats[j] = val
        if is_seated[j]:
            val += 1
            upd_func = appr
        else:
            upd_func = appl
        for dj in MOVE:
            nj = j + dj
            if seats[nj] > val and nj not in updated:
                upd_func((val, nj))
    clrq()
    # print(p, i, res)
    # pg(seats)

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
ps = list(map(int, input().split()))
rem_num = {}

for i in range(1, n*n+1):
    rem_num[i] = min([(i-1)//n, n - (i-1)//n - 1, (i-1) % n, n - (i-1) % n - 1])


ans = 0
for p in ps:
    # print(f"{p} {rem_num} {rem_num[p]}")
    ans += rem_num[p]
    queue = [p]
    while len(queue) > 0:
        q = queue.pop(0)
        if q - n > 0 and rem_num[q] < rem_num[q-n]:
            queue.append(q-n)
            rem_num[q - n] = rem_num[q]
        if q + n < n*n+1 and rem_num[q] < rem_num[q+n]:
            queue.append(q+n)
            rem_num[q + n] = rem_num[q]
        if q % n != 1 and rem_num[q] < rem_num[q-1]:
            queue.append(q-1)
            rem_num[q - 1] = rem_num[q]
        if q % n != 0 and rem_num[q] < rem_num[q+1]:
            queue.append(q+1)
            rem_num[q + 1] = rem_num[q]
        

print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    from collections import deque
    #input = sys.stdin.readline
    n = int(input())
    p = [int(i)-1 for i in input().split()]
    c = [[1]*n for _ in range(n)] 
    d = [[0]*n for _ in range(n)] 
    for x in range(n):
        for y in range(n):
            d[y][x] = min(x, n-x-1, y, n-y-1)
    ans = 0
    
    for i in p:
        x, y = i%n, i//n
        c[y][x] = 0
        ans += d[y][x]
        que = deque([[x, y]])
        while que:
            x, y = que.pop()
            for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
                nx, ny = x+dx, y+dy
                if 1<=nx<n-1 and 1<=ny<n-1:
                    if d[y][x]+c[y][x]<d[ny][nx]:
                        d[ny][nx] = d[y][x]+c[y][x]
                        if nx==1 or nx==n-2 or ny==1 or ny==n-2: continue
                        que.append([nx, ny])
    
    return print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
count=0
plist=list(map(int,input().split()))
check=[1]*(n**2)
def chec(k):
  if k-n<1 or n+n>n**2 or k%n==0 or k%n==1:
    check[k-1]=0
#for p in plist:

print(check)

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)]
    q = [0] * (n ** 2)
    ans = 0
    for pi in p:
        ans += dp[pi - 1]
        c[pi - 1] = 0
        q[0] = pi
        p = 0
        l = 1
        while p != l:
            yx = q[p] - 1
            p += 1
            score = dp[yx] + c[yx]
            for my, mx in m:
                myx = my * n + mx + yx
                if 0 < my // n < n - 1 and 0 < mx % n < n - 1:
                    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:
import numba
import numpy as np
#N = int(input())
#P = np.array([int(c)-1 for c in input().split()])

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

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

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

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

n, *ppp = map(int, sys.stdin.buffer.read().split())

n2 = n + 2
seats = [-1] * n2
row_base0 = list(range(n))
row_base1 = [-1] + row_base0 + [-1]
row_base0.reverse()
row_base2 = [-1] + row_base0 + [-1]
row_base = [min(a, b) for a, b in zip(row_base1, row_base2)]

for i in range(n):
    ud = min(i, n - 1 - i)
    seats.extend(min(a, ud) for a in row_base)
seats.extend([-1] * n2)

is_seated = [False] * n2
is_seated.extend(([False] + [True] * n + [False]) * n)
is_seated.extend([False] * n2)


def pg(aaa):
    for i in range(0, n2 ** 2, n2):
        print(aaa[i:i + n2])
    print()


ans = 0
MOVE = (-n2, -1, 1, n2)
for p in ppp:
    i, j = divmod(p - 1, n)
    i = (i + 1) * n2 + j + 1
    res = seats[i]
    ans += res
    is_seated[i] = False

    updated = {i + di for di in MOVE}
    q = deque([(res, ni) for ni in updated])
    updated.add(i)

    while q:
        val, j = q.popleft()
        if seats[j] <= val:
            continue
        seats[j] = val
        ist = is_seated[j]
        for dj in MOVE:
            nj = j + dj
            if nj in updated:
                continue
            updated.add(nj)
            if ist:
                nv = val + 1
                if seats[nj] > nv:
                    q.append((nv, nj))
            else:
                if seats[nj] > val:
                    q.appendleft((val, nj))
    # print(p, i, res)
    # pg(seats)

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()
        if res != 600 and unlike >= res:
            continue
        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: 
                    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 sys
input = sys.stdin.readline
from collections import deque
def main():
    N = int(input())
    P = list(map(int, input().split()))
    graph = {}
    exits = [0 for _ in range(N**2)]
    for i in range(N**2):
        graph[i] = set()
    ans = 0
    for i in range(N**2):
        current = P[i]-1
        up = current // N
        left = current % N
        down = N - (current // N) - 1
        right = N - (current % N) - 1
        d1 = min(up, left, down, right)
        d2 = N**2
        if d1 > 0:
            dist = [-1 for _ in range(N**2)]
            dist[current] = 0
            que = deque([])
            que.append(current)
            while len(que) != 0:
                v = que.popleft()
                for node in graph[v]:
                    if dist[node] != -1:continue
                    dist[node] = dist[v]+1
                    up2 = node // N
                    left2 = node % N
                    down2 = N - (node // N) - 1
                    right2 = N - (node % N) - 1
                    d2 = min(d2, up2, left2, down2, right2)
                    que.append(node)
        ans += min(d1, d2)
        exits[current] = 1
        if current == 0:
            for v in [P[i], current+N]:
                if exits[v] == 1:
                    graph[current].add(v)
                graph[v].add(current)
        elif current == N-1:
            for v in [P[i]-2, current+N]:
                if exits[v] == 1:
                    graph[current].add(v)
                graph[v].add(current)
        elif current == N**2-N:
            for v in [P[i], current-N]:
                if exits[v] == 1:
                    graph[current].add(v)
                graph[v].add(current)
        elif current == N**2-1:
            for v in [P[i]-2, current-N]:
                if exits[v] == 1:
                    graph[current].add(v)
                graph[v].add(current)
        elif current < N:
            for v in [P[i]-2, P[i], current+N]:
                if exits[v] == 1:
                    graph[current].add(v)
                graph[v].add(current)
        elif current > N**2-N-1:
            for v in [P[i]-2, P[i], current-N]:
                if exits[v] == 1:
                    graph[current].add(v)
                graph[v].add(current)
        elif (current) % N == 0:
            for v in [P[i], current-N, current+N]:
                if exits[v] == 1:
                    graph[current].add(v)
                graph[v].add(current)
        elif P[i] % N == 0:
            for v in [P[i]-2, current-N, current+N]:
                if exits[v] == 1:
                    graph[current].add(v)
                graph[v].add(current)
        else:
            for v in [P[i]-2, P[i], current-N, current+N]:
                if exits[v] == 1:
                    graph[current].add(v)
                graph[v].add(current)
    print(ans)
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

import sys
readline = sys.stdin.readline
read = sys.stdin.read

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


solve()

Submission status: 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)]
    q = [0] * (n ** 2)
    ans = 0
    for pi in p:
        y, x = divmod(pi - 1, n)
        ans += dp[y][x]
        c[y][x] = 0
        q[0] = pi
        p = 0
        l = 1
        while p == l:
            y, x = divmod(q[p] - 1, n)
            p += 1
            score = dp[y][x] + c[y][x]
            for my, mx in m:
                my += y
                mx += x
                if 0 < my < n - 1 and 0 < mx < n - 1:
                    if dp[my][mx] > score:
                        dp[my][mx] = score
                        q[l] = my * n + mx + 1
                        l += 1
    print(ans)
    return


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

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()
        if unlike >= res:
            continue
        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: 
                    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 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:
            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:
            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:
            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:
            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 deque

N = int(input())
offset = 0
field = N
people = [[1 for _ in range(field)] for _ in range(field)]
HL = [0] *N
HR = [0]*N
Hcnt = 0
for P in input().split():
    visited = [[600 for _ in range(field)] for _ in range(field)]
    seen = [[0 for _ in range(field)] for _ in range(field)]

    nowx = (int(P)-1)//N
    nowy = (int(P)-1)%N
    todo = deque()
    todo.append((nowx,nowy))
    mv = [(0,1),(1,0),(-1,0),(0,-1)]

    seen[nowx][nowy] += 1
    people[nowx][nowy] = 0
    visited[nowx][nowy] = 0
    flag = False
    while len(todo) > 0:
        nowx, nowy = todo.popleft()
        for i in range(len(mv)):
            dx, dy = mv[i]
            nx = nowx + dx 
            ny = nowy + dy

            if nx >= N or nx < 0 or ny >= N or ny < 0: 
                    continue               
            if visited[nx][ny] > visited[nowx][nowy] + people[nx][ny]:
                visited[nx][ny] = visited[nowx][nowy] + people[nx][ny]
            seen[nx][ny] +=1
            if seen[nx][ny] > 3:continue
            todo.append((nx,ny))
        if flag:
            break

    for n in range(N):
        HL[n] = visited[n][0]
        HR[n] = visited[n][N-1]
    Hcnt += min(min(visited[0]),min(visited[N-1]),min(HL),min(HR))

print(Hcnt)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

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


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

    DP = [[0]*N for i in range(N)]

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

    def shoot(i,j,s,S):
        if not j*N+i+1 in S:
            S.add((i,j))
            if DP[i][j]>s:
                DP[i][j] = s
                if i>0:
                    shoot(i-1,j,s+1,S)
                if i<N-1:
                    shoot(i+1,j,s+1,S)
                if j>0:
                    shoot(i,j-1,s+1,S)
                if j<N-1:
                    shoot(i,j+1,s+1,S)
            elif DP[i][j]==-1:
                if i>0:
                    shoot(i-1,j,s,S)
                if i<N-1:
                    shoot(i+1,j,s,S)
                if j>0:
                    shoot(i,j-1,s,S)
                if j<N-1:
                    shoot(i,j+1,s,S)

            

    ans = 0
    for p in P:
        i = (p-1)%N
        j = (p-1)//N
        ans += DP[i][j]
        S = set()
        Q = deque([((i,j),DP[i][j])])
        flag = True
        while len(Q)>0:
            A,s = Q.pop()
            a,b = A
            if flag:
                flag=False
                S.add(b*N+a+1)
                if a>0:
                    Q.append(((a-1,b),s))
                if a<N-1:
                    Q.append(((a+1,b),s))
                if b>0:
                    Q.append(((a,b-1),s))
                if b<N-1:
                    Q.append(((a,b+1),s))
            elif not b*N+a+1 in S:
                S.add(b*N+a+1)
                if DP[a][b]>s:
                    DP[a][b]=s
                    if a>0:
                        Q.append(((a-1,b),s+1))
                    if a<N-1:
                        Q.append(((a+1,b),s+1))
                    if b>0:
                        Q.append(((a,b-1),s+1))
                    if b<N-1:
                        Q.append(((a,b+1),s+1))
                if DP[a][b]==-1:
                    if a>0:
                        Q.append(((a-1,b),s))
                    if a<N-1:
                        Q.append(((a+1,b),s))
                    if b>0:
                        Q.append(((a,b-1),s))
                    if b<N-1:
                        Q.append(((a,b+1),s))
        DP[i][j] = -1
        #for i in range(N):
        #    print(*DP[i])
        #print()
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
print(3|6)

Submission status: Wrong Answer

Solution code:
cin = open(0).read().strip().split('\n')
n = int(cin[0])
p = list(map(int, cin[1].split(' ')))

from collections import deque
q = deque()

space = [1]*(n*n)

dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in p:
    row, col = divmod(pi-1, n)

    q.clear()
    q.append((row, col))

    dist = [-1]*(n*n)
    dist[row*n+col] = 0

    ret = list()
    while q:
        ph, pw = q.popleft()
        for dyi, dxi in zip(dy,dx):
            if 0<=ph+dyi<n and 0<=pw+dxi<n:
                if dist[(ph+dyi)*n+(pw+dxi)] == -1:
                    q.append((ph+dyi,pw+dxi))
                    dist[(ph+dyi)*n+(pw+dxi)] = dist[ph*n+pw]+space[(ph+dyi)*n+(pw+dxi)]
            else:
                ret.append(dist[ph*n+pw])
    ans += min(ret)
    space[row*n + col] = 0

print(ans)

Submission status: Wrong Answer

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

import sys
readline = sys.stdin.readline
read = sys.stdin.read

n,*p = map(int,read().split())
N = n*n

dist = [0]*N

for a in range(n):
    for b in range(n):
        dist[a*n+b] = min(a,n-1-a,b,n-1-b)

#print(dist)


#ans = [0]*N
ans = 0
iru = [1]*N

move = [-n,-1,1,n]
for pi in p:
    pi -= 1

    ans += dist[pi]
    iru[pi] = 0

    q = [pi]
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        for i in move:
            if i==1 and v%n==n-1: continue
            if i==-1 and v%n==0: continue
            nv = v+i
            if 0 <= nv < N and dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        
                    
    #print(dist)        

print(ans)
if n==3: print(1)

Submission status: Wrong Answer

Solution code:
def chk_1st_row(p_l, N):
  if(p_l <= N):
    return True
  else:
    return False

def chk_last_row(p_l, N):
  if(N**2-N+1 <= p_l):
    return True
  else:
    return False
  
def chk_isle(p_l, N):
  if(p_l % N == 0 or p_l % N == 1):
    return True
  else:
    return False

def chk_right(p_l, p, N):
  # print(p_l, ',', N * (p_l // N + 1))
  for i in range(p_l+1, N * (p_l // N + 1) + 1):
    if(i in p):
      return True
  return False

def chk_left(p_l, p, N):
  # print(p_l, N * (p_l // N))
  for i in range(N * (p_l // N) + 1, p_l):
    if(i in p):
      return True
  return False

def chk_front(p_l, p, N):
  while(p_l > 0):
    p_l -= N
    if(p_l in p):
      return True
      break
  return False

def chk_rear(p_l, p, N):
  while(p_l < N**2):
    p_l += N
    if(p_l in p):
      return True
      break
  return False

N = int(input())
count = 0

in_theater = []
for i in range(1,N**2+1):
  in_theater.append(i)

p = list(map(int,input().split()))
# print(p)
for i in range(N**2):
  p_l = p[0]
  p.remove(p[0])
  if(chk_1st_row(p_l, N)):
    continue
  elif(chk_last_row(p_l, N)):
    continue
  elif(chk_isle(p_l, N)):
    continue
  elif(not(chk_right(p_l, p, N))):
    continue
  elif(not(chk_left(p_l, p, N))):
    continue
  elif(not(chk_front(p_l, p, N))):
    continue
  elif(not(chk_rear(p_l, p, N))):
    continue
  count += 1
  # print(p_l, count)
print(count)