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
sys.setrecursionlimit(1010100)
n=int(input())
*p,=map(int, input().split())
#n=3
#p=[1, 3, 7, 9, 5, 4, 8, 6, 2]

for i in range(n*n):p[i]-=1
seats=[
    [min(i,j,n-i-1,n-j-1)for i in range(n)] 
    for j in range(n)
    ]

check=[[False]*n for _ in range(n)]
exist=[[1]*n for _ in range(n)]
dxy=[(0,1),(1,0),(-1,0),(0,-1)]
def dfs(pi):
    global check,exist
    i=pi%n
    j=pi//n
    res=seats[i][j]
    check[i][j]=True
    for dx,dy in dxy:
        idx,jdy=i+dx,j+dy
        if 0<=idx<n and 0<=jdy<n and (not check[idx][jdy]):
            res=min(res,dfs(idx+jdy*n)+exist[idx][jdy])
        if res==0:
            return res
    seats[i][j]=res
    return res
ans=0
for pi in p:
    check=[[False]*n for _ in range(n)]
    ans+=dfs(pi)
    exist[pi%n][pi//n]=0
print(ans)

Submission status: Wrong Answer

Solution code:
from numba import njit
import numpy as np
@njit
def dfs(v,c,h,stay,todo):
    # hを更新
    todo[0]=v
    now=0
    while now>=0:
        vv=todo[now]
        now-=1
        x,y=divmod(vv,n)
        for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
            nx,ny=x+dx,y+dy
            if 0<=nx<n and 0<=ny<n:
                nv=nx*n+ny
                if h[nv]>h[vv]+stay[vv]:
                    h[nv]=h[vv]
                    now+=1
                    todo[now]=nv

@njit
def main(n,p):
    h=[min(i//n,n-i//n-1,i%n,n-i%n-1) for i in range(n**2)]
    h=np.array(h,np.int32)
    stay=np.full(n*n,1,np.int32)
    todo=np.zeros(n*n,np.int32)
    ans=0
    for v in p:
        c=h[v]
        ans+=c
        stay[v]=0
        dfs(v,c,h,stay,todo)
    print(ans)

if __name__=='__main__':
    n=int(input())
    p=np.array(list(map(int,input().split())),np.int32)
    p-=1
    main(n,p)

Submission status: Wrong Answer

Solution code:
from numba import njit
import numpy as np
@njit
def func(x,h):
    # hを更新
    c=h[x]
    h[x]=-1
    todo=[[x,c]]
    seen={x}
    while todo:
        v,c=todo.pop()
        x,y=divmod(v,n)
        for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
            nx,ny=x+dx,y+dy
            if 0<=nx<n and 0<=ny<n:
                nv=nx*n+ny
                if nv in seen:continue
                if h[nv]==-1:
                    todo.append([nv,c])
                elif h[nv]>c:
                    h[nv]=c
                    todo.append([nv,c+1])
                seen.add(nv)
@njit
def main(n,p):
    h=np.array([min(i//n,n-i//n-1,i%n,n-i%n-1) for i in range(n**2)],np.int32)
    ans=0
    for x in p:
        ans+=h[x]
        func(x,h)
    print(ans)
if __name__=='__main__':
    n=int(input())
    p=np.array(list(map(int,input().split())),np.int32)
    p-=1
    main(n,p)

Submission status: Wrong Answer

Solution code:
from numba import njit
import numpy as np
@njit
def func(x,c,h,stay):
    # hを更新
    todo=[[x,c]]
    seen={x}
    while todo:
        v,c=todo.pop()
        nvs=[v+n,v-n]
        if v%n<n-1:nvs.append(v+1)
        if v%n>0:nvs.append(v-1)
        for nv in nvs:
            if nv<0 or n**2<=nv:continue
            if nv in seen:continue
            if h[nv]>c:
                h[nv]=c
                todo.append([nv,c+stay[nv]])
            seen.add(nv)

@njit
def main(n,p):
    h=[min(i//n,n-i//n-1,i%n,n-i%n-1) for i in range(n**2)]
    h=np.array(h)
    stay=np.full(n**2,1)
    ans=0

    for x in p:
        c=h[x-1]
        ans+=c
        stay[x-1]=0
        func(x-1,c,h,stay)
    print(ans)

    #for i in range(n):
    #    print(h[i*n:(i+1)*n])
if __name__=='__main__':
    n=int(input())
    p=list(map(int,input().split()))
    main(n,p)

Submission status: Wrong Answer

Solution code:
n=int(input())
p=list(map(int,input().split()))
h=[min(i//n,n-i//n-1,i%n,n-i%n-1) for i in range(n**2)]
ans=0
def func(x):
    # hを更新
    c=h[x]
    h[x]=-1
    todo=[[x,c]]
    seen=set(())
    while todo:
        v,c=todo.pop()
        nvs=[]
        if v+n<n**2:nvs.append(v+n)
        if v%n<n-1 and v+1<n**2:nvs.append(v+1)
        if v-n>=0:nvs.append(v-n)
        if v%n!=0 and v-1>=0:nvs.append(v-1)
        for nv in nvs:
            if nv in seen:continue
            if h[nv]==-1:
                todo.append([nv,c])
            elif h[nv]>c:
                h[nv]=c
                todo.append([nv,c+1])
            seen.add(nv)
for x in p:
    ans+=h[x-1]
    func(x-1)
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
p=list(map(int,input().split()))
h=[min(i//n,n-i//n-1,i%n,n-i%n-1) for i in range(n**2)]
ans=0
def func(x):
    # hを更新
    c=h[x]
    h[x]=-1
    todo=[x]
    seen=[0]*(n**2)
    while todo:
        v=todo.pop()
        nvs=[]
        if v+n<n**2:nvs.append(v+n)
        if v%n<n-1 and v+1<n**2:nvs.append(v+1)
        if v-n>=0:nvs.append(v-n)
        if v%n!=0 and v-1>=0:nvs.append(v-1)
        for nv in nvs:
            if seen[nv]==1:continue
            if h[nv]==-1:
                todo.append(nv)
            elif h[nv]>c:
                h[nv]=c
            seen[nv]=1
for x in p:
    ans+=h[x-1]
    func(x-1)
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

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

    # 観客がいる場合は1、いない場合は0
    # 行数、列数は最大でも500なので、int16で十分
    flag_row = np.ones((N, N), dtype=np.int16)
    flag_col = np.ones((N, N), dtype=np.int16)

    ans = 0
    for a in A:
        row, col = (a - 1) // N, (a - 1) % N
        # 退席する観客の行、列にいる観客の情報
        fr = flag_row[row]
        fc = flag_col[col]
        # 自分は退席するのでフラグを消す
        fr[col] = 0
        fc[row] = 0
        # 上下左右それぞれに退席するときの人数を計算し、最小値を選択
        sum_left   = fr[:col].sum()
        sum_right  = fr[col+1:].sum()
        sum_up     = fc[:row].sum()
        sum_bottom = fc[row+1:].sum()

        ans += min(sum_left, sum_right, sum_up, sum_bottom)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np

def resolve(N,Ps):
    dislike_counter = 0

    seats = np.ones(N*N, dtype=np.int64)
    seats_sq = seats.reshape((N,N))

    for p in Ps:
        no = p-1
        seats[no] = 0
        i, j = no // N, no % N 

        up = seats_sq[:i,j].sum()
        down = seats_sq[i+1:, j].sum()
        left = seats_sq[i, :j].sum()
        right = seats_sq[i, j+1:].sum()

        dislike_counter += min((up, down, left, right))
        
    return dislike_counter


def main():
    N = int(input())
    Ps = list(map(int, input().split()))
    ans = resolve(N, Ps)

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
def main():
    n = int(input())
    p = list(map(int, input().split()))
    for i in range(len(p)):
        p[i] -= 1
    
    to_outsides = [[0]*n for _ in range(n)]
    not_exist = [[False]*n for _ in range(n)]
    
    for i in range(n):
        for j in range(n):
            to_outside = [i,n-1-i,j,n-1-j]
            to_outsides[i][j] = min(to_outside)
    
    directions = [[-1,0],[1,0],[0,-1],[0,1]]
    
    all_loss = 0
    answer = 0
    for i, person in enumerate(p):
        exited = [person//n, person%n]
        answer += to_outsides[exited[0]][exited[1]]
        not_exist[exited[0]][exited[1]] = True
        seen = []
        seen.append([exited[0],exited[1]])
        todo = deque([exited])
        renews = []
        while len(todo)>0:
            now = todo.pop()
            renews.append(now)
            for direction in directions:
                try:
                    checking = [now[0]+direction[0],now[1]+direction[1]]
                    to_outsides[checking[0]][checking[1]]
                except:
                    continue
                if [checking[0],checking[1]] not in seen:
                    if ((not_exist[checking[0]][checking[1]] == True and  to_outsides[checking[0]][checking[1]]==to_outsides[now[0]][now[1]])or\
                     to_outsides[checking[0]][checking[1]]>to_outsides[now[0]][now[1]]):
                        todo.append([checking[0],checking[1]])
                        seen.append([checking[0],checking[1]])
                    else:
                        seen.append([checking[0],checking[1]])
                        
        for renew in renews:
            if to_outsides[renew[0]][renew[1]] != 0:
                to_outsides[renew[0]][renew[1]]-=1
    print(answer)
main()

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
  n = int(input())
  p = list(map(int, input().split()))
  for i in range(len(p)):
      p[i] -= 1

  to_outsides = [[0 for _ in range(n)] for _ in range(n)]
  not_exist = [["■" for _ in range(n)] for _ in range(n)]


  for i in range(n):
      for j in range(n):
          to_outside = [i,n-1-i,j,n-1-j]
          to_outsides[i][j] = min(to_outside)

  directions = [[-1,0],[1,0],[0,-1],[0,1]]

  answer = 0
  for i, person in enumerate(p):
      exited = [person//n, person%n]
      answer += to_outsides[exited[0]][exited[1]]
      not_exist[exited[0]][exited[1]] = "□"
      seen = deque()
      seen.append([exited[0],exited[1]])
      todo = deque([exited])
      renews = []
      while len(todo)>0:
          now = todo.pop()
          renews.append(now)
          for direction in directions:
              try:
                  checking = [now[0]+direction[0],now[1]+direction[1]]
                  to_outsides[checking[0]][checking[1]]
              except:
                  continue
              if [checking[0],checking[1]] not in seen:
                  if ((not_exist[checking[0]][checking[1]] == "□" and  to_outsides[checking[0]][checking[1]]==to_outsides[now[0]][now[1]])or\
                   to_outsides[checking[0]][checking[1]]>to_outsides[now[0]][now[1]]):
                      todo.append([checking[0],checking[1]])
                      seen.append([checking[0],checking[1]])
                  else:
                      seen.append([checking[0],checking[1]])

      for renew in renews:
          if to_outsides[renew[0]][renew[1]] != 0:
              to_outsides[renew[0]][renew[1]]-=1
  print(answer)

main()

Submission status: Wrong Answer

Solution code:
from collections import deque
import copy
def main():
  n = int(input())
  p = list(map(int, input().split()))
  for i in range(len(p)):
      p[i] -= 1

  to_outsides = [[0 for _ in range(n)] for _ in range(n)]
  not_exist = [["■" for _ in range(n)] for _ in range(n)]


  for i in range(n):
      for j in range(n):
          to_outside = [i,n-1-i,j,n-1-j]
          to_outsides[i][j] = min(to_outside)

  directions = [[-1,0],[1,0],[0,-1],[0,1]]

  all_loss = 0
  answer = 0
  for i, person in enumerate(p):
      exited = [person//n, person%n]
      answer += to_outsides[exited[0]][exited[1]]
      not_exist[exited[0]][exited[1]] = "□"
      seen = []
      seen.append([exited[0],exited[1]])
      todo = deque([exited])
      renews = []
      while len(todo)>0:
          now = todo.pop()
          renews.append(now)
          for direction in directions:
              try:
                  checking = [now[0]+direction[0],now[1]+direction[1]]
                  to_outsides[checking[0]][checking[1]]
              except:
                  continue
              if [checking[0],checking[1]] not in seen:
                  if ((not_exist[checking[0]][checking[1]] == "□" and  to_outsides[checking[0]][checking[1]]==to_outsides[now[0]][now[1]])or\
                   to_outsides[checking[0]][checking[1]]>to_outsides[now[0]][now[1]]):
                      todo.append([checking[0],checking[1]])
                      seen.append([checking[0],checking[1]])
                  else:
                      seen.append([checking[0],checking[1]])

      for renew in renews:
          if to_outsides[renew[0]][renew[1]] != 0:
              to_outsides[renew[0]][renew[1]]-=1
  print(answer)

main()

Submission status: Wrong Answer

Solution code:
import numpy as np


def resolve(N, Ps):
    seats = np.arange(N**2, dtype=np.int32)
    seats_sq = seats.reshape((N,N))

    hate_count = 0
    def n2ij(n):
        i = n // N
        j = n % N
        return (i,j)

    for p in Ps:
        seats[p-1] = -1
        i, j = n2ij(p-1)

        up = seats_sq[0:i, j]
        up = up[up > -1]
        down = seats_sq[i+1:, j]
        down = down[down > -1]
        left = seats_sq[i, 0:j]
        left = left[left > -1]
        right = seats_sq[i, j+1:]
        right = right[right > -1]

        hate_count += min([up, down, left, right], key=lambda houkou: houkou.size).size
    
    return hate_count

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

    ans = resolve(N, Ps)

    print(ans)

def test():
    N = 3
    Ps = list(map(int, "1 3 7 9 5 4 8 6 2".split()))
    expected = 1
    ans = resolve(N, Ps)
    if ans == expected:
        print("OK") 
    else:
        print(f"ans={ans} but expected={expected}")

    N = 4
    Ps = list(map(int, "6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8".split()))
    expected = 3
    ans = resolve(N, Ps)
    if ans == expected:
        print("OK") 
    else:
        print(f"ans={ans} but expected={expected}")

    N = 6
    Ps = list(map(int, "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".split()))
    expected = 11
    ans = resolve(N, Ps)
    if ans == expected:
        print("OK") 
    else:
        print(f"ans={ans} but expected={expected}")

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

Submission status: Wrong Answer

Solution code:
def resolve(N,Ps):
    seats = dict()
    rev = dict()
    for i in range(N):
        for j in range(N):
            no = i*N + j+1
            seats[(i+1, j+1)] = i*N + j+1
            rev[no] = (i+1, j+1)

    dislike = set()


    def leave(p):
        nonlocal seats
        i, j = rev[p]
        seats[(i,j)] = 0


        ue  = [(ii, j) for ii in range(1, i)]
        shita  = [(ii, j) for ii in range(i+1, N+1)]
        hidari  = [(i, jj) for jj in range(1, j)]
        migi  = [(i, jj) for jj in range(j+1, N+1)]

        #print(f"({i},{j}) ue {ue}")
        #print(f"({i},{j}) shita {shita}")
        #print(f"({i},{j}) hidari {hidari}")
        #print(f"({i},{j}) migi {migi}")

        houkous = [ue, shita, hidari, migi]

        houkou = min(houkous, key=lambda houkou: len([index for index in houkou if seats[index] != 0]))

        pairs = set((p, seats[index]) for index in houkou if seats[index] != 0)

        return pairs
    
    for p in Ps:
        pairs = leave(p)
        dislike |= pairs
        
    return dislike


def main():
    N = int(input())
    Ps = list(map(int, input().split()))
    ans = resolve(N, Ps)

    print(len(ans))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from numba import njit
import numpy


def read():
    N = int(input().strip())
    P = list(map(int, input().strip().split()))
    return N, P


@njit
def init_Q(N, Q):
    for i in range(N):
        for j in range(N):
            k = i * N + j
            Q[k, 0] = min([i, j, N-i-1, N-j-1]) + 1
            Q[k, 1] = 1   


@njit
def dfs(N, Q, visited, p):
    visited[p] = True
    D = [N, -N, 1, -1]
    for dp in D:
        np = p + dp
        if 0 <= np < N*N and abs(np%N - p%N) < N-1:
            # 4隣接が除去済みマスなら、コストなしで到達可能
            if not visited[np] and Q[np][0] > Q[p][0] + Q[np][1]:
                Q[np][0] = Q[p][0] + Q[np][1]
                dfs(N, Q, visited, p)


@njit
def np_solve(N, P, INF=10**9):
    Q = numpy.empty((N*N, 2), dtype=numpy.int32)
    init_Q(N, Q)
    D = [N, -N, 1, -1]
    visited = numpy.zeros(N*N, dtype=numpy.bool_)
    ans = 0

    for p in P:
        r = INF
        for dp in D:
            np = p + dp
            if 0 <= np < N*N and abs(np%N - p%N) < N-1:
                r = min(r, abs(Q[np][0]))
            else:
                r = 0
        ans += r
        Q[p][0] = r
        Q[p][1] = 0
        visited[:] = False
        dfs(N, Q, visited, p)
    return ans


def solve(N, P):
    # Q[p][0]: 行動の最初にそのマスを踏んだ場合の、脱出までの最短コスト
    # Q[p][1]: 退室済みなら0
    P = numpy.array(P, dtype=numpy.int) - 1
    return np_solve(N, P)


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("{}".format(outputs))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from numba import njit
import numpy


def read():
    N = int(input().strip())
    P = list(map(int, input().strip().split()))
    return N, P

@njit
def init_Q(N, Q):
    for i in range(N):
        for j in range(N):
            k = i * N + j
            Q[k, 0] = min([i, j, N-i-1, N-j-1]) + 1
            Q[k, 1] = 1   


@njit
def dfs(N, Q, visited, p):
    visited[p] = True
    D = [N, -N, 1, -1]
    for dp in D:
        np = p + dp
        if 0 <= np < N*N and abs(np%N - p%N) < N-1:
            # 4隣接が除去済みマスなら、コストなしで到達可能
            if Q[np][0] > Q[p][0] + Q[np][1]:
                Q[np][0] = Q[p][0] + Q[np][1]
                dfs(N, Q, visited, p)
    
@njit
def np_solve(N, P, INF=10**9):
    Q = numpy.empty((N*N, 2), dtype=numpy.int32)
    init_Q(N, Q)
    D = [N, -N, 1, -1]
    visited = numpy.zeros(N*N, dtype=numpy.bool_)
    ans = 0

    for p in P:
        r = INF
        for dp in D:
            np = p + dp
            if 0 <= np < N*N and abs(np%N - p%N) < N-1:
                r = min(r, abs(Q[np][0]))
            else:
                r = 0
        ans += r
        Q[p][0] = r
        Q[p][1] = 0
        visited[:] = False
        dfs(N, Q, visited, p)
    return ans


def solve(N, P):
    # Q[p][0]: 行動の最初にそのマスを踏んだ場合の、脱出までの最短コスト
    # Q[p][1]: 退室済みなら0
    P = numpy.array(P, dtype=numpy.int) - 1
    return np_solve(N, P)


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("{}".format(outputs))

Submission status: Wrong Answer

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


def read():
    N = int(input().strip())
    P = list(map(int, input().strip().split()))
    return N, P


def print_map(N, Q):
    for i in range(N):
        print(Q[i*N:(i+1)*N])


def solve(N, P, INF=10**9):
    P = [p-1 for p in P]
    D = [N, -N, 1, -1]
    # Q[p]: 行動の最初にそのマスを踏んだ場合の、脱出までの最短コスト
    Q = [0 for _ in P]
    # LEFT[p]: 取り除いたらTrue
    LEFT = [False for _ in P]
    NN = N * N
    ans = 0

    for i in range(N):
        for j in range(N):
            k = i * N + j
            Q[k] = min(i, j, N-i-1, N-j-1) + 1
    
    for p in P:
        q = deque()
        r = INF
        for dp in D:
            np = p + dp
            if 0 <= np < NN and abs(np%N - p%N) < N-1:
                r = min(r, Q[np])
            else:
                r = 0
        
        ans += r

        LEFT[p] = True
        Q[p] = r
        q.append(p)
        while q:
            pp = q.popleft()
            for dp in D:
                np = pp + dp
                if 0 <= np < NN and abs(np%N - pp%N) < N-1:
                    # 4隣接が除去済みマスなら、コストなしで到達可能
                    if LEFT[np] and Q[np] > Q[pp]:
                        Q[np] = Q[pp]
                        q.append(np)
                    # elif not LEFT[np] and Q[np] > Q[pp] + 1:
                    #    Q[np] = Q[pp] + 1
                    #    q.append(np)
    return ans


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("{}".format(outputs))

Submission status: Wrong Answer

Solution code:
#import numpy as np
import sys
sys.setrecursionlimit(20000)
[n], *e = [[*map(int, t.split())] for t in open(0)]
#n = 500
# np.random.seed(seed=64)
#ppp = [x + 1 for x in np.random.permutation(n * n).astype(np.int32)]
#e = [ppp]
# print(ppp)


viewers = set(range(1, n**2 + 1))
mem = {x: min((x - 1) % n, (n - x) % n, (x - 1)//n, n - 1 - (x - 1)//n)
       for x in range(1, n**2 + 1)}


def directions(x):
    tmp = []
    if x % n != 1:
        tmp.append(x - 1)
    if x % n > 0:
        tmp.append(x + 1)
    if (x - 1)//n > 0:
        tmp.append(x - n)
    if (x - 1)//n < n - 1:
        tmp.append(x + n)
    return tmp


ans = 0

for x in e[0]:
    visited = set()
    visited.add(x)

    def fill(x):
        queue = []
        for k in directions(x):
            if k not in visited:
                visited.add(k)
                if mem[k] > mem[x] + (x in viewers):
                    mem[k] = mem[x] + (x in viewers)
                    queue.append(k)
        for node in queue:
            fill(node)

    ans += mem[x]
    viewers.remove(x)
    fill(x)

print(ans)

Submission status: Wrong Answer

Solution code:
[n], *e = [[*map(int, t.split())] for t in open(0)]
viewers = set(range(1, n**2 + 1))
mem = {x: min((x - 1) % n, (n - x) % n, (x - 1)//n, n - 1 - (x - 1)//n)
       for x in range(1, n**2 + 1)}


def directions(x):
    tmp = []
    if x % n != 1:
        tmp.append(x - 1)
    if x % n > 0:
        tmp.append(x + 1)
    if (x - 1)//n > 0:
        tmp.append(x - n)
    if (x - 1)//n < n - 1:
        tmp.append(x + n)
    return tmp


ans = 0

for x in e[0]:
    visited = set()
    visited.add(x)

    def fill(x):
        queue = [x]
        while queue:
            current = queue.pop(0)
            for k in directions(current):
                if k not in visited:
                    visited.add(k)
                    queue.append(k)
                    if mem[k] > mem[current] + (current in viewers):
                        mem[k] = mem[current] + (current in viewers)

    ans += mem[x]
    viewers.remove(x)
    fill(x)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
p = list(map(int, input().split()))

distance = [[min(i, j, n - i - 1, n - j - 1) for i in range(n)] for j in range(n)]
check = [[1] * n for i in range(n)]
p = [((i - 1) // n, (i - 1) % n) for i in p]

def move(x,y,nx,ny):
    if distance[nx][ny] > distance[x][y] + check[nx][ny]:
        distance[nx][ny] = distance[x][y] + check[nx][ny]
        d.append((nx,ny))

ans = 0
for i, j in p:
    ans += distance[j][i]
    d=deque()
    d.append((j,i))
    check[j][i] = 0
    while len(d):
        x, y = d.popleft()
        if x!=0:
            move(x,y,x-1,y)
        if x!=n-1:
            move(x,y,x+1,y)
        if y!=0:
            move(x,y,x,y-1)
        if y!=n-1:
            move(x,y,x,y+1)

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
from collections import deque


def solve():
    N = int(input())
    ps = map(int, input().split())

    sheets = np.ndarray(shape=(N, N), dtype=int)

    for i in range(N):
        rmax = min(i, N-1-i)
        sheets[i] = np.array([min(j, N-1-j, rmax) for j in range(N)])

    total = 0
    q = deque()

    def push(q, x, y, v, passed):
        for px, py in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:
            if (px, py) in passed:
                continue
            if px < 0 or N <= px or py < 0 or N <= py:
                continue
            passed.add((px, py))
            q.append((px, py, v))

    for p in ps:
        y, x = divmod(p-1, N)
        v = sheets[x][y]
        total += v
        sheets[x][y] = -1

        passed = {(x, y)}
        push(q, x, y, v, passed)

        while q:
            x, y, v = q.popleft()
            sv = sheets[x][y]
            if sv == -1:
                push(q, x, y, v, passed)
            elif v < sv:
                sheets[x][y] = v
                push(q, x, y, v+1, passed)

    return total


def main():
    print(solve())


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N, *P = map(int, open(0).read().split())

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

def move(fr, to):
    if dp[to] > dp[fr] + memo[fr]:
        dp[to] = dp[fr] + memo[fr]
        S.append(to)

ans = 0
for p in P:
    ans += dp[p]
    memo[p] = 0

    S = [p]
    while S:
        v = S.pop()

        q, r = divmod(v - 1, N)
        if r != 0:
            move(v, v - 1)
        if r != N - 1:
            move(v, v + 1)
        if q < N - 1:
            move(v, v + N)
        if q >= 1:
            move(v, v - N)

print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import sys

# from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.buffer.read
from heapq import heappop, heappush
from collections import defaultdict

sys.setrecursionlimit(10 ** 7)
# import math
# from itertools import product, accumulate, combinations, product
# import bisect# lower_bound etc
import numpy as np
# from copy import deepcopy
from collections import deque
import numba

N = int(input())
P = np.array(list(map(int, sysread().split())))
#@numba.njit("void(i8,i8[:])")
@numba.njit
def run():
    seats = np.zeros((N,N), dtype=np.int32)
    seen = np.zeros((N,N), dtype=np.int32)  # there is a person : 1
    up, down = 0, N - 1
    dist = 0
    while True:
        seats[up, up:down+1] = dist
        seats[down, up:down+1] = dist
        seats[up:down+1, up] = dist
        seats[up:down+1, down] = dist
        up += 1
        down -= 1
        dist += 1
        if up > down:
            break

    ret = 0
    ###
    for i in range(N ** 2):
        # print(seats)
        cur_i, cur_j = (P[i] - 1) // N, (P[i] - 1) % N
        ret += seats[cur_i,cur_j]
        seen[cur_i,cur_j] = 1
        stack = [(seats[cur_i,cur_j], (cur_i, cur_j))]
        while stack:
            del_val, (cur_i, cur_j) = stack.pop()
            for i, j in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                n_i = cur_i + i
                n_j = cur_j + j
                if 0 <= n_i <= N - 1 and 0 <= n_j <= N - 1:
                    if seen[cur_i, cur_j]:
                        if del_val < seats[n_i, n_j]:
                            seats[n_i, n_j] = del_val
                            stack.append((del_val, (n_i, n_j)))
                    else:
                        if del_val + 1 < seats[n_i, n_j]:
                            seats[n_i, n_j] = del_val + 1
                            stack.append((del_val, (n_i, n_j)))

    print(ret)


if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
from numba import njit
import numpy as np


def cc_export():
    @njit('(i4, i4, i4[:], i4[:], i4[:], i4)')
    def update(n, w, que, there, cost, pos):
        pass
        # que[0] = pos
        # i, l = 0, 1
        # while i < l:
        #     pos = que[i]
        #     i += 1
        #     c = cost[pos]
        #     t = there[pos]
        #     k = c + t
        #     for df in list([-w, w, -1, 1]):
        #         pp = pos + df
        #         if cost[pp] > k:
        #             cost[pp] = k
        #             que[l] = pp
        #             l += 1

    @njit('(i4, i4[:])')
    def main(n, p):
        w = n + 2
        que = np.zeros(4 * w * w, dtype=np.int32)
        there = np.ones(w * w, dtype=np.int32)
        # there = np.array([
        #     1 if 1 <= i and i <= n and 1 <= j and j <= n else 0
        #     for j in range(w) for i in range(w)
        # ],
        #                  dtype=np.int32)
        cost = np.array([
            -1 if i == 0 or i == n + 1 or j == 0 or j == n + 1 else min(
                i - 1, n - i, j - 1, n - j) for j in range(w) for i in range(w)
        ],
                        dtype=np.int32)

        ans = 0
        for pos in p:
            # v = list(map(lambda x: ' ' if x == 0 else '*', list(there)))
            # for i in range(w):
            #     print(' '.join(v[i * w:(i + 1) * w]))
            # print(cost.reshape((w, w)))
            # print("add", cost[pos], "for", divmod(pos, w))
            ans += cost[pos]
            there[pos] = 0
            update(n, w, que, there, cost, pos)
        return ans

    from numba.pycc import CC
    cc = CC('solution')
    cc.export('update', '(i4, i4, i4[:], i4[:], i4[:], i4)')(update)
    cc.export('main', '(i4, i4[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        sys.exit(0)

    def transform(t):
        y, x = divmod(int(t) - 1, n)
        return (y + 1) * (n + 2) + (x + 1)

    from solution import update, main
    n = int(input())
    p = np.array(list(map(transform, input().split())), dtype=np.int32)
    print(main(n, p))