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:
def main():
    from collections import deque
    import sys
    input = sys.stdin.readline
    n = int(input())
    l = list(map(int,input().split()))
    check = [[1]*n for i in range(n)]
    d = [[float("INF")]*n for i in range(n)]

    dx = [1,-1,0,0]
    dy = [0,0,1,-1]
    d[0] = [0]*n
    d[-1] = [0]*n
    for i in range(n):
        d[i][0] = 0
        d[i][-1] = 0
    for i in range(1,n-1):
        for j in range(1,n-1):
            d[i][j] = min(d[i+1][j],d[i-1][j],d[i][j+1],d[i][j-1])+1

    def update(x,y):
        check[x][y] = 0
        a = check[x][y]
        for i in range(4):
            nx = x+dx[i]
            ny = y+dy[i]
        
            if 0 <= nx < n and 0 <= ny < n:
                a = max(a,d[nx][ny])
        check[x][y] = min(check[x][y],a)
        q = deque([])
        q.append((x,y))
        while q:
            bx,by = q.popleft()

            for i in range(4):
                nx = bx+dx[i]
                ny = by+dy[i]

                if 0 <= nx < n and 0 <= ny < n:
                    if d[nx][ny] > d[bx][by]+check[bx][by]:
                        d[nx][ny] = d[bx][by]
                        q.append((nx,ny))
                    

    ans = 0
    for i in l:
        i -= 1
        x = i//n
        y = i%n
        ans += d[x][y]
        update(x,y)
    print(ans)

if __name__ =="__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections
from heapq import *

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**3
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    P = LI()

    seat = [[1] * N for _ in range(N)]
    zero = [[1] * N for _ in range(N)]

    ans = 0

    for i in P:
        x = (i-1) % N
        y = (i-1) // N
        min_cnt = INF
        if x == 0 or x == N-1 or y == 0 or y == N-1:
            min_cnt = 0
        else:

            dp = [[INF] * N for _ in range(N)]
            d = 0
            f = 0
            q = collections.deque()
            q.append((f,d,x,y))
            dp[x][y] = 0
            while q:
                f,d,i,j = q.popleft()
                if d > min(x,N-x,y,N-y): break
                for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                    if not(0 <= i+di < N and 0 <= j+dj < N):
                        min_cnt = min(min_cnt,f)
                        continue
                    if zero[i+di][j+dj] == 0:
                        min_cnt = min(min_cnt,f)
                        continue
                    e = seat[i+di][j+dj]
                    if dp[i+di][j+dj] > f+e:
                        dp[i+di][j+dj] = f+e
                        q.append((f+e,d+1,i+di,j+dj))

        seat[x][y] = 0
        if min_cnt == 0:
            zero[x][y] = 0
        ans += min_cnt
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
l = list(map(int,input().split()))
check = [[1]*n for i in range(n)]
d = [[float("INF")]*n for i in range(n)]

dx = [1,-1,0,0]
dy = [0,0,1,-1]
d[0] = [0]*n
d[-1] = [0]*n
for i in range(n):
    d[i][0] = 0
    d[i][-1] = 0
for i in range(1,n-1):
    for j in range(1,n-1):
        d[i][j] = min(d[i+1][j],d[i-1][j],d[i][j+1],d[i][j-1])+1

def update(x,y):
    check[x][y] = 0
    a = check[x][y]
    for i in range(4):
        nx = x+dx[i]
        ny = y+dy[i]
    
        if 0 <= nx < n and 0 <= ny < n:
            a = max(a,d[nx][ny])
    check[x][y] = min(check[x][y],a)
    q = deque([])
    q.append((x,y))
    while q:
        bx,by = q.popleft()

        for i in range(4):
            nx = bx+dx[i]
            ny = by+dy[i]

            if 0 <= nx < n and 0 <= ny < n:
                if d[nx][ny] > d[bx][by]+check[bx][by]:
                    d[nx][ny] = d[bx][by]
                    q.append((nx,ny))
                

ans = 0
for i in l:
    i -= 1
    x = i//n
    y = i%n
    ans += d[x][y]
    update(x,y)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
d=deque([1, 2, 3])
d.append(4)      # [1, 2, 3, 4]
x=d.pop()        # x=4, [1, 2, 3]

def f(x, y):
  d=deque([[x, y]])
  sumi=[[-1]*(N+2)]+[[-1]+[0]*N+[-1] for _ in range(N)]+[[-1]*(N+2)]
  cand=kazu[x][y]
  while d:
    data=d.popleft()
    cand=min(cand, kazu[data[0]][data[1]])
    if sumi[data[0]-1][data[1]]==0 and hito[data[0]-1][data[1]]==0:
      d.append([data[0]-1, data[1]])
      sumi[data[0]-1][data[1]]=1
    if sumi[data[0]+1][data[1]]==0 and hito[data[0]+1][data[1]]==0:
      d.append([data[0]+1, data[1]])
      sumi[data[0]+1][data[1]]=1
    if sumi[data[0]][data[1]-1]==0 and hito[data[0]][data[1]-1]==0:
      d.append([data[0], data[1]-1])
      sumi[data[0]][data[1]-1]=1
    if sumi[data[0]][data[1]+1]==0 and hito[data[0]][data[1]+1]==0:
      d.append([data[0], data[1]+1])
      sumi[data[0]][data[1]+1]=1
  return cand

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

hito=[[-1]*(N+2)]+[[-1]+[1]*N+[-1] for _ in range(N)]+[[-1]*(N+2)]

kazu=[[0]*(N+2) for _ in range(N+2)]
for i in range(1, N+1):
  for j in range(1, N+1):
    kazu[i][j]=min(i-1, j-1, N-i, N-j)

ans=0
for p in P:
  x=(p-1)%N+1
  y=(p-1)//N+1
  ans+=f(x, y)
  hito[x][y]=0
  
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
d=deque([1, 2, 3])
d.append(4)      # [1, 2, 3, 4]
x=d.pop()        # x=4, [1, 2, 3]

def f(x, y):
  d=deque([[x, y]])
  sumi=[[-1]*(N+2)]+[[-1]+[1]*N+[-1] for _ in range(N)]+[[-1]*(N+2)]
  cand=kazu[x][y]
  while d:
    data=d.popleft()
    cand=min(cand, kazu[data[0]][data[1]])
    sumi[data[0]][data[1]]=0
    if sumi[data[0]-1][data[1]]==1 and hito[data[0]-1][data[1]]==0:
      d.append([data[0]-1, data[1]])
    if sumi[data[0]+1][data[1]]==1 and hito[data[0]+1][data[1]]==0:
      d.append([data[0]+1, data[1]])
    if sumi[data[0]][data[1]-1]==1 and hito[data[0]][data[1]-1]==0:
      d.append([data[0], data[1]-1])
    if sumi[data[0]][data[1]+1]==1 and hito[data[0]][data[1]+1]==0:
      d.append([data[0], data[1]+1])
  return cand

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

hito=[[-1]*(N+2)]+[[-1]+[1]*N+[-1] for _ in range(N)]+[[-1]*(N+2)]

kazu=[[0]*(N+2) for _ in range(N+2)]
for i in range(1, N+1):
  for j in range(1, N+1):
    kazu[i][j]=min(i-1, j-1, N-i, N-j)

ans=0
for p in P:
  x=(p-1)%N+1
  y=(p-1)//N+1
  ans+=f(x, y)
  hito[x][y]=0
  
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
buff_readline = sys.stdin.buffer.readline


def read_int():
    return tuple(buff_readline())


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

def slv(N, P):
    M = N+2
    cost = [0] * M**2
    occupy = [True] * M**2
    for i in range(N):
        im = i * (M+1)
        for j in range(N):
            cost[im + j + 1] = min(i, j, N-i-1, N-j-1)

    ds = [-1, 1, -M, M]
    ans = 0
    for p in P:
        p -= 1
        x = p // N
        y = p % N
        p = x * M + y + M + 1
        ans += cost[p]
        occupy[p] = False
        s = [p]
        while s:
            pi = s.pop()
            for d in ds:
                ni = pi + d
                nc = cost[pi] + (1 if occupy[pi] else 0)
                if nc < cost[ni]:
                    s.append(ni)
                    cost[ni] = nc
    return ans


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

    import random
    N = 500
    P = list(range(1, N**2+1))
    random.shuffle(P)
    print(slv(N, P))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
Ps = list(map(int, input().split()))

def hw(p):
    h = (p-1)//n
    w = (p-1)%n
    return h,w

def toP(h,w):
    return h * n + w + 1

fs = [[0]*n for i in range(n)]
## フロアフィールドを作る
for i in range(n):
    x = min(i,n-1-i)
    for j in range(n):
        y = min(j,n-1-j)
        fs[i][j] = min(x,y)

ans = 0
mvs = [(1,0),(-1,0),(0,1),(0,-1)]
occupied = [[1]*n for i in range(n)]

for p in Ps:
    h,w = hw(p) 
    # 自分と、周りの中で最小のものを選ぶ
    a = fs[h][w]
    for dh,dw in mvs:
        if 0<=h+dh<n and 0<=w+dw<n:
            a = min(a, fs[h+dh][w+dw] + occupied[h+dh][w+dw])       
    ans += a
    # print(p,"hw",h,w,"dist",a)
    occupied[h][w] = 0
    q = deque([])
    q.append(p)
    while len(q) > 0: #pを起点にBFS
        p_ = q.popleft()
        h, w = hw(p_)
        dist = fs[h][w]
        for dh,dw in mvs:
            if 0<=h+dh<n and 0<=w+dw<n:
                if dist+occupied[h+dh][w+dw] < fs[h+dh][w+dw]:
                    q.append(toP(h+dh,w+dw))
                    fs[h+dh][w+dw] = dist + occupied[h+dh][w+dw]

                
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
Ps = list(map(int, input().split()))

def hw(p):
    h = (p-1)//n
    w = (p-1)%n
    return h,w

def toP(h,w):
    return h * n + w + 1

fs = [[0]*n for i in range(n)]
## フロアフィールドを作る
for i in range(n):
    x = min(i,n-1-i)
    for j in range(n):
        y = min(j,n-1-j)
        fs[i][j] = min(x,y)

ans = 0
mvs = [(1,0),(-1,0),(0,1),(0,-1)]
vacant = [[False]*n for i in range(n)]

for p in Ps:
    h,w = hw(p) 
    # 自分と、周りの中で最小のものを選ぶ
    a = fs[h][w]
    for dh,dw in mvs:
        if 0<=h+dh<n and 0<=w+dw<n:
            if vacant[h+dh][w+dw]:
                a = min(a, fs[h+dh][w+dw])
            else:
                a = min(a, fs[h+dh][w+dw] + 1)       
    ans += a
    # print(p,"hw",h,w,"dist",a)
    vacant[h][w] = True
    q = deque([])
    q.append(p)
    while len(q) > 0: #pを起点にBFS
        p_ = q.popleft()
        h, w = hw(p_)
        dist = fs[h][w]
        for dh,dw in mvs:
            if 0<=h+dh<n and 0<=w+dw<n:
                if vacant[h+dh][w+dw]: #隣がvacant
                    if dist < fs[h+dh][w+dw]:
                        q.append(toP(h+dh,w+dw))
                        fs[h+dh][w+dw] = dist
                else: #隣がoccupied
                    if dist + 1 < fs[h+dh][w+dw]:
                        q.append(toP(h+dh,w+dw))
                        fs[h+dh][w+dw] = dist + 1 
    
    # for r in fs:
    #     print(*r)
    # for p in vacant:
    #     print(*p)
    # print("---------")
                        
                
print(ans)

Submission status: Wrong Answer

Solution code:

N=int(input())
A=list(map(int,input().strip().split()))

def getCoordinate(n):
    x=n%N
    if x==0:
        x=N
    y=int(n/N)
    if n%N!=0:
        y=y+1
    return x-1,y-1

class Query :
    def __init__(self):
        self.x1=0
        self.y1=0
        self.x2=0
        self.y2=0
#// A function to update the 2D BIT 
def updateBIT(BIT,x,y,val):
    y1=0;
    while(x<=N):
        y1=y
        while(y1<=N):
            BIT[x][y1]+=val
            y1+=(y1 & -y1)
        x += (x & -x)
#def updateBIT(BIT, x,  y, val) :
#    M=N
#    while(x<=M):
#        while(y<=M):
#            BIT[x][y]+=val
#            y+= (y& -y)
#        x+=(x& -x)
#    return; 
  
#// A function to get sum from (0, 0) to (x, y) 
def getSum( BIT, x,  y) :
    sum = 0; 
    y1=0
    while(x>0):
        y1=y
        while(y1>0):
            sum += BIT[x][y1]; 
            y1 -= (y1 &-y1)
        x -= x&-x        
    return sum; 
  
#// A function to create an auxiliary matrix 
#// from the given input matrix 
def constructAux( mat, aux):  
    #// Initialise Auxiliary array to 0 
    for i in range(N+1):
        for j in range(1,N):
            aux[i][j]=0; 
    #// Construct the Auxiliary Matrix 
    for i in range(N+1):
        for j in range(1,N+1):
            aux[i][j] = mat[N-j][i-1]; 
    return;
  
#// A function to construct a 2D BIT 
def construct2DBIT(mat, BIT):
    #// Create an auxiliary matrix 
    #aux[N+1][N+1]; 
    aux=[]
    for i in range(N+1):
        aux.append([0]*(N+1))
    constructAux(mat, aux)
  
    #// Initialise the BIT to 0 
    for i in range(1,N+1):
    #for (int i=1; i<=N; i++) 
        for j in range(1,N+1):
        #for (int j=1; j<=N; j++) 
            BIT[i][j] = 0; 
    for j in range(1,N+1):  
    #for (int j=1; j<=N; j++) 
        for i in range(1,N+1):  
        #for (int i=1; i<=N; i++)  
           # // Creating a 2D-BIT using update function 
           # // everytime we/ encounter a value in the 
           # // input 2D-array 
            v1 = getSum(BIT, i, j); 
            v2 = getSum(BIT, i, j-1); 
            v3 = getSum(BIT, i-1, j-1); 
            v4 = getSum(BIT, i-1, j); 
  
            #// Assigning a value to a particular element 
            #// of 2D BIT 
            updateBIT(BIT, i, j, aux[i][j]-(v1-v2-v4+v3));   
    return; 

#// A function to answer the queries

def answerQueries(q,BIT):
    #for (int i=0; i<m; i++) 
        x1 =q.x1 + 1; 
        y1 = q.y1 + 1; 
        x2 = q.x2 + 1; 
        y2 = q.y2 + 1; 
     
        ans = getSum(BIT, x2, y2)-getSum(BIT, x2, y1-1)- getSum(BIT, x1-1, y2)+getSum(BIT, x1-1, y1-1); 
        if ans<0:
            return 0
        return ans;   

B=[]
for i in range(N):
    B.append([0]*N)
j=0
for i in range(N):
    for k in range(N):
        B[i][k]=1
        j+=1
#int BIT[N+1][N+1]; 
#    construct2DBIT(mat, BIT); 
BIT=[]
for i in range(N+2):
    BIT.append([0]*(N+2))
construct2DBIT(B,BIT)
cnt=0
q=Query()
for i in range(0,len(A)):
    #print("___________________________________________________")
    p=A[i]
    x,y=getCoordinate(p)
    ans1,ans2,ans3,ans4=0,0,0,0
    if x!=0:
        q.x1=0
        q.x2=x-1
        q.y1=y
        q.y2=y
        #print(q.x1,q.y1,q.x2,q.y2)
        ans1=answerQueries(q,BIT)
    if x!=N-1:
        q.x1=x+1
        q.x2=N-1
        q.y1=y
        q.y2=y
        #ans2=getSum(BIT,3,y)-getSum(BIT,x,y)
        #print(q.x1,q.y1,q.x2,q.y2)
        ans2=answerQueries(q,BIT)
    if y!=0:
        q.x1=x
        q.x2=x
        q.y1=0
        q.y2=y-1
        #print(q.x1,q.y1,q.x2,q.y2)
        ans3=answerQueries(q,BIT)
    if y!=N-1:
        q.x1=x
        q.x2=x
        q.y1=y+1
        q.y2=N-1
        #print(q.x1,q.y1,q.x2,q.y2)
        ans4=answerQueries(q,BIT)
    cnt+=min(ans1,ans2,ans3,ans4)
    updateBIT(BIT,x+1,y+1,-1)
print(cnt)

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

d = [None] * (n**2)
for i in range(n):
    for j in range(n):
        d[i*n+j] = min(i, n-1-i, j, n-1-j)
vacant = [False] * (n**2)

ans = 0
for pos in p:
    pos -= 1
    ans += d[pos]
    v = d[pos]
    q = [(v, pos)]
    while q:
        v,pos = q.pop()
        for diff in (-n, n, -1, 1):
            ppos = pos + diff
            if ppos<0 or ppos>=n*n:
                continue
            if d[ppos]>v:
                d[ppos] = v
                nv = v+1 if not vacant[ppos] else v
                q.append((nv, ppos))
    vacant[pos] = True
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
imput = sys.stdin.readline


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

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

occ = [True] * (n * n)
ans = 0
for start in p:
    start -= 1
    q = deque([start])
    ans += cost[start]
    occ[start] = False
    while q:
        ij = q.popleft()
        i, j = divmod(ij, n)

        nxt_ij = (i + 1) * n + (j + 0)
        if not(0 <= i + 1 < n and 0 <= j + 0 < n):
            continue
        if not occ[ij] and cost[nxt_ij] > cost[ij]:
                cost[nxt_ij] = cost[ij]
                q.append(nxt_ij)
        elif cost[nxt_ij] > cost[ij] + 1:
                cost[nxt_ij] = cost[ij] + 1
                q.append(nxt_ij)
              
        nxt_ij = (i - 1) * n + (j + 0)
        if not(0 <= i - 1 < n and 0 <= j + 0 < n):
            continue
        if not occ[ij] and cost[nxt_ij] > cost[ij]:
                cost[nxt_ij] = cost[ij]
                q.append(nxt_ij)
        elif cost[nxt_ij] > cost[ij] + 1:
                cost[nxt_ij] = cost[ij] + 1
                q.append(nxt_ij)

        nxt_ij = (i + 0) * n + (j + 1)
        if not(0 <= i + 0 < n and 0 <= j + 1 < n):
            continue
        if not occ[ij] and cost[nxt_ij] > cost[ij]:
                cost[nxt_ij] = cost[ij]
                q.append(nxt_ij)
        elif cost[nxt_ij] > cost[ij] + 1:
                cost[nxt_ij] = cost[ij] + 1
                q.append(nxt_ij)

        nxt_ij = (i + 0) * n + (j - 1)
        if not(0 <= i + 0 < n and 0 <= j - 1 < n):
            continue
        if not occ[ij] and cost[nxt_ij] > cost[ij]:
                cost[nxt_ij] = cost[ij]
                q.append(nxt_ij)
        elif cost[nxt_ij] > cost[ij] + 1:
                cost[nxt_ij] = cost[ij] + 1
                q.append(nxt_ij)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
imput = sys.stdin.readline


n = int(input())
p = list(map(int, input().split()))
diff = (n, -n, 1, -1)

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

occ = [True] * (n * n)
ans = 0
for start in p:
    start -= 1
    q = deque([start])
    ans += cost[start]
    occ[start] = False

    while q:
        ij = q.popleft()
        i, j = divmod(ij, n)
        for d_ij in diff:
            di, dj = divmod(d_ij, n)
            nxt_ij = ij + d_ij
            if not(0 <= i + di < n and 0 <= j + dj < n):
                continue
            if not occ[ij]:
                if cost[nxt_ij] > cost[ij]:
                    cost[nxt_ij] = cost[ij]
                    q.append(nxt_ij)
            else:
                if cost[nxt_ij] > cost[ij] + 1:
                    cost[nxt_ij] = cost[ij] + 1
                    q.append(nxt_ij)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
imput = sys.stdin.readline


diff = ((0, 1), (0, -1), (1, 0), (-1, 0))
n = int(input())
p = list(map(int, input().split()))

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

occ = [True] * (n * n)
ans = 0
for start in p:
    start -= 1
    q = deque([start])
    ans += cost[start]
    occ[start] = False
    cost[start] -= 1
    while q:
        ij = q.popleft()
        i, j = divmod(ij, n)
        for di, dj in diff:
            nxt_i = i + di
            nxt_j = j + dj
            nxt_ij = nxt_i * n + nxt_j
            if not(0 <= nxt_i < n and 0 <= nxt_j < n):
                continue
            elif not occ[ij] and not occ[nxt_ij] and cost[nxt_ij] > cost[ij]:
                cost[nxt_ij] = cost[ij]
                q.append(nxt_ij)
            elif cost[nxt_ij] > cost[ij] + 1:
                cost[nxt_ij] = cost[ij] + 1
                q.append(nxt_ij)

print(ans)

Submission status: Wrong Answer

Solution code:

import queue
import sys
import numpy as np
from numba import njit
input = sys.stdin.buffer.readline


@njit('(i4,i4[:])', cache=True)
def main(N, aa):
    mm = [[0] * N for _ in range(N)]

    for i in range((N + 1) // 2):
        j = N - i - 1

        for x in range(i, j + 1):
            mm[i][x] = i
            mm[j][x] = i
            mm[x][i] = i
            mm[x][j] = i

    is_none = [[False] * N for _ in range(N)]

    ans = 0

    for a in aa:
        x = (a - 1) % N
        y = (a - 1) // N

        ans += mm[y][x]

        is_none[y][x] = True

        mm[y][x] -= 1

        q = []
        q.append((x, y, mm[y][x]))
        idx = 0
        L = 1
        while idx < L:
            x0, y0, n = q[idx]

            if x0 != 0:
                if is_none[y0][x0 - 1] and mm[y0][x0 - 1] > n:
                    mm[y0][x0 - 1] = n
                    q.append((x0 - 1, y0, n))
                    L += 1
                elif not is_none[y0][x0 - 1] and mm[y0][x0 - 1] > n + 1:
                    mm[y0][x0 - 1] = n + 1
                    q.append((x0 - 1, y0, n + 1))
                    L += 1

            if x0 != N - 1:
                if is_none[y0][x0 + 1] and mm[y0][x0 + 1] > n:
                    mm[y0][x0 + 1] = n
                    q.append((x0 + 1, y, n))
                    L += 1
                elif not is_none[y0][x0 + 1] and mm[y0][x0 + 1] > n + 1:
                    mm[y0][x0 + 1] = n + 1
                    q.append((x0 + 1, y, n + 1))
                    L += 1

            if y0 != 0:
                if is_none[y0 - 1][x0] and mm[y0 - 1][x0] > n:
                    mm[y0 - 1][x0] = n
                    q.append((x0, y0 - 1, n))
                    L += 1
                elif not is_none[y0 - 1][x0] and mm[y0 - 1][x0] > n + 1:
                    mm[y0 - 1][x0] = n + 1
                    q.append((x0, y0 - 1, n + 1))
                    L += 1

            if y0 != N - 1:
                if is_none[y0 + 1][x0] and mm[y0 + 1][x0] > n:
                    mm[y0 + 1][x0] = n
                    q.append((x0, y0 + 1, n))
                    L += 1
                elif not is_none[y0 + 1][x0] and mm[y0 + 1][x0] > n + 1:
                    mm[y0 + 1][x0] = n + 1
                    q.append((x0, y0 + 1, n + 1))
                    L += 1

            idx += 1

    return ans


if __name__ == "__main__":
    N = int(input())
    aa = np.array(list(map(int, input().split())), np.int32)
    print(main(N, aa))

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**3
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    P = LI()

    seat = [[1] * N for _ in range(N)]
    zero = [[1] * N for _ in range(N)]

    ans = 0

    for i in P:
        x = (i-1) % N
        y = (i-1) // N

        min_cnt = INF
        for dd in (((1,0),(0,1)),((1,0),(0,-1)),((-1,0),(0,1)),((-1,0),(0,-1))):
            dp = [[INF] * N for _ in range(N)]
            d = 0
            q = collections.deque()
            q.append((x,y,d))
            dp[x][y] = 0
            while q:
                i,j,d = q.popleft()
                for di,dj in dd:
                    if not(0 <= i+di < N and 0 <= j+dj < N):
                        break
                    if zero[i+di][j+dj] == 0:
                        break
                    e = seat[i+di][j+dj]
                    if dp[i+di][j+dj] > d+e:
                        dp[i+di][j+dj] = d+e
                        q.append((i+di,j+dj,d+e))
                else:
                    continue
                break
            min_cnt = min(min_cnt,d)
        seat[x][y] = 0
        if min_cnt == 0:
            q = collections.deque()
            q.append((x,y))
            zero[x][y] = 0
            while q:
                i,j = q.popleft()
                for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                    if not(0 <= i+di < N and 0 <= j+dj < N): continue
                    if seat[i+di][j+dj] == 1 or zero[i+di][j+dj] == 0: continue
                    zero[i+di][j+dj] = 0
                    q.append((i+di,j+dj))
        ans += min_cnt
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
p = [int(i) - 1 for i in input().split()]
d = [[min(i, n - 1 - i,j, n - 1 - j) + 1 for j in range(n)]
     for i in range(n)]
emp = [[1] * n for _ in range(n)]


def get(i, j):
    if 0 <= i < n and 0 <= j < n:
        return d[i][j]
    else:
        return 0


def app(i, j):
    if 0 <= i < n and 0 <= j < n and visited[i][j]:
        q.append((i, j))
        visited[i][j] = False


def ap(i, j):
    if 0 <= i < n and 0 <= j < n and visited[i][j]:
        q.appendleft((i, j))
        visited[i][j] = False

ans = 0
for pp in p:
    i, j = pp // n, pp % n
    ans += d[i][j] - 1
    emp[i][j] = 0
    visited = [[True] * n for _ in range(n)]
    visited[i][j] = False
    q = deque([(i, j)])
    while q:
        i, j = q.popleft()
        new = min(get(i + 1, j), get(i - 1, j),
                  get(i, j + 1), get(i, j - 1)) + emp[i][j]
        if new < d[i][j]:
            d[i][j] = new
            if emp[i][j]:
                app(i+1, j)
                app(i-1, j)
                app(i, j+1)
                app(i, j - 1)
            else:
                ap(i+1, j)
                ap(i-1, j)
                ap(i, j+1)
                ap(i, j-1)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
p = [int(i) - 1 for i in input().split()]
d = [[min(i, n - 1 - i,j, n - 1 - j) + 1 for j in range(n)]
     for i in range(n)]
emp = [[1] * n for _ in range(n)]


def get(i, j):
    if 0 <= i < n and 0 <= j < n:
        return d[i][j]
    else:
        return 0


def app(i, j):
    if 0 <= i < n and 0 <= j < n and visited[i][j]:
        q.append((i, j))
        visited[i][j] = False

ans = 0
for pp in p:
    i, j = pp // n, pp % n
    ans += d[i][j] - 1
    emp[i][j] = 0
    visited = [[True] * n for _ in range(n)]
    visited[i][j] = False
    q = [(i, j)]
    for qq in q:
        i, j = qq
        new = min(get(i + 1, j), get(i - 1, j),
                  get(i, j + 1), get(i, j - 1)) + emp[i][j]
        if new < d[i][j]:
            d[i][j] = new
            app(i+1, j)
            app(i-1, j)
            app(i, j+1)
            app(i, j-1)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
#import numpy

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

digtmp = [[0, 1], [1, 0], [0, -1], [-1, 0]]

def main():
    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
    out = [[0]*N for _ in range(N)]
    for p in P:
        i, j = (p-1)//N, (p-1)%N
        seetij = seet[i][j]
        ans += seetij
        out[i][j] = 1
        que = deque([[i, j]])
        check = [[0]*N for _ in range(N)]

        for k in range(4):
            to = [i+digtmp[k][0], j+digtmp[k][1]]
            if 0 <= to[0] < N and 0 <= to[1] < N:
                if seetij < seet[to[0]][to[1]]:
                    seet[to[0]][to[1]] = seetij
                    que.append(to)

        for _ in range(pow(500,2)+1):
            fr = que.popleft()
            seetfr = seet[fr[0]][fr[1]]
            check[fr[0]][fr[1]] = 1
            status = out[fr[0]][fr[1]]
            for k in range(4):
                to = [fr[0]+digtmp[k][0], fr[1]+digtmp[k][1]]
                if 0 <= to[0] < N and 0 <= to[1] < N:
                    checkto = check[to[0]][to[1]]
                    if seetfr < seet[to[0]][to[1]] and checkto == 0:
                        seet[to[0]][to[1]] = (status == 0)*(seetfr+1) + (status == 1)*seetfr
                        que.append(to)
            if len(que) == 0:
                break

    #print(nseet)
    print(ans)


if __name__ == "__main__":
    main()