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


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

    Kcost = [0] * (N * N)
    for sn in range(N * N):
        row, clm = divmod(sn, N)
        Kcost[sn] = min(row, N - row - 1, clm, N - clm - 1)

    Vseat = [0] * (N * N)
    Kcount = 0

    for sn in P:
        csn = sn - 1
        Kcount += Kcost[csn]
        Vseat[csn] = 1
        queue = [csn]

        while queue:
            qsn = queue.pop()
            for dsn in (1, -1, N, -N):
                cdsn = qsn + dsn

                if qsn % N == 0 and dsn == -1 or qsn % N == N - 1 and dsn == 1  or cdsn < 0 or cdsn >= N:
                    continue

                if Vseat[cdsn] and Kcost[cdsn] > Kcost[qsn]:
                    Kcost[cdsn] = Kcost[qsn]
                    queue.append(cdsn)

                if Vseat[cdsn] == 0 and Kcost[cdsn] > Kcost[qsn] + 1:
                    Kcost[cdsn] = Kcost[qsn] + 1
                    queue.append(cdsn)

    print(Kcount)


if __name__ == '__main__':
    main()

sys.exit()

Submission status: Wrong Answer

Solution code:
from collections import deque
import numpy as np

def main():
  N=int(input())
  S=list(map(int,input().split()))
  count=0
  P=np.ones((N*N+1))
  d=np.zeros((N*N+1))
  que=deque()
  for i in range(N*N):
    player=S[i]
    P[player]=0
    que.clear()
    que.append((player,0))
    d[player]=i+1

    finish=-1
    while que:
      kouho,j=que.popleft()
      if kouho%N==0:
        finish=1
        break
      if kouho%N==1:
        finish=1
        break
      if kouho+N>N*N:
        finish=1
        break
      if kouho<N:
        finish=1
        break

      if d[kouho+N]<i+1:
        if P[kouho+N]>0:
          que.append((kouho+N,j+1))
          d[kouho+N]=i+1
        else:
          que.appendleft((kouho+N,j))
          d[kouho+N]=i+1

      if d[kouho-N]<i+1:
        if P[kouho-N]>0:
          que.append((kouho-N,j+1))
          d[kouho-N]=i+1
        else:
          que.appendleft((kouho-N,j))
          d[kouho-N]=i+1

      if d[kouho+1]<i+1:
        if P[kouho+1]>0:
          que.append((kouho+1,j+1))
          d[kouho+1]=i+2
        else:
          que.appendleft((kouho+1,j))
          d[kouho+1]=i+1

      if d[kouho-1]<i+1:
        if P[kouho-1]>0:
          que.append((kouho-1,j+1))
          d[kouho-1]=i+1
        else:
          que.appendleft((kouho-1,j))
          d[kouho-1]=i+1
    count+=j

  print(count)

main()

Submission status: Wrong Answer

Solution code:
from collections import deque
import numpy as np

def main():
  N=int(input())
  S=list(map(int,input().split()))
  count=0
  P=np.ones((N*N+1),dtype=np.int32)
  d=np.zeros((N*N+1),dtype=np.int32)
  que=deque()
  for i in range(N*N):
    player=S[i]
    P[player]=0
    que.clear()
    que.append((player,0))
    d[player]=i+1

    finish=-1
    while que:
      kouho,j=que.popleft()
      if kouho%N==0:
        finish=1
        break
      if kouho%N==1:
        finish=1
        break
      if kouho+N>N*N:
        finish=1
        break
      if kouho<N:
        finish=1
        break

      if d[kouho+N]<i+1:
        if P[kouho+N]==1:
          que.append((kouho+N,j+1))
          d[kouho+N]=i+1
        else:
          que.appendleft((kouho+N,j))
          d[kouho+N]=i+1

      if d[kouho-N]<i+1:
        if P[kouho-N]==1:
          que.append((kouho-N,j+1))
          d[kouho-N]=i+1
        else:
          que.appendleft((kouho-N,j))
          d[kouho-N]=i+1

      if d[kouho+1]<i+1:
        if P[kouho+1]==1:
          que.append((kouho+1,j+1))
          d[kouho+1]=i+2
        else:
          que.appendleft((kouho+1,j))
          d[kouho+1]=i+1

      if d[kouho-1]<i+1:
        if P[kouho-1]==1:
          que.append((kouho-1,j+1))
          d[kouho-1]=i+1
        else:
          que.appendleft((kouho-1,j))
          d[kouho-1]=i+1
    count+=j

  print(count)

main()

Submission status: Wrong Answer

Solution code:
def main():
  N=int(input())
  S=list(map(int,input().split()))
  count=0
  P=[0]*(N*N+1)
  for j in range(N*N):
    P[S[j]]=j+1
  d=[-1]*(N*N+1)
  que=[]
  for i in range(N*N):
    player=S[i]
    hayasa=P[player]
    que.append((player,0))
    d[player]=i

    finish=-1
    while que:
      kouho,j=que.pop()
      if kouho%N==0:
        finish=1
        break
      if kouho%N==1:
        finish=1
        break
      if kouho+N>N*N:
        finish=1
        break
      if kouho<N:
        finish=1
        break

      if d[kouho+N]<i:
        if P[kouho+N]>hayasa:
          que.append((kouho+N,j+1))
          d[kouho+N]=i
        else:
          que.append((kouho+N,j))
          d[kouho+N]=i

      if d[kouho-N]<i:
        if P[kouho-N]>hayasa:
          que.append((kouho-N,j+1))
          d[kouho-N]=i
        else:
          que.append((kouho-N,j))
          d[kouho-N]=i

      if d[kouho+1]<i:
        if P[kouho+1]>hayasa:
          que.append((kouho+1,j+1))
          d[kouho+1]=i
        else:
          que.append((kouho+1,j+1))
          d[kouho+1]=i

      if d[kouho-1]<i:
        if P[kouho-1]>hayasa:
          que.append((kouho-1,j+1))
          d[kouho-1]=i
        else:
          que.append((kouho-1,j))
          d[kouho-1]=i
    count+=j

  print(count)

main()

Submission status: Wrong Answer

Solution code:
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(map(int, input().split()))
mod=1000000007

#+++++

def main():
	n = int(input())
	nn = [[min(i+1,j+1,n-i,n-j) for j in range(n)] for i in range(n)]
	is_sit = [[True] * n for _ in range(n)]
	cc = [[0]*n for _ in range(n)]
	
	#b , c = tin()
	pl = lin()
	ans = 0
	for p in pl:
		x, y = (p-1) // n, (p-1) % n
		ans += nn[x][y]-1
		is_sit[x][y] = False
		nn[x][y]-=1
		q = [(x, y, nn[x][y])]
		while q:
			(x, y, v) = q.pop()
			for dx,dy in ([-1,0], [0,-1], [1,0], [0,1]):
				if x+dx < 0 or x +dx >= n or y + dy < 0 or y + dy >= n:
					continue
				iss = 1 if is_sit[x+dx][y+dy] else 0
				if nn[x+dx][y + dy] <= v + iss:
					continue
				nn[x+dx][y+dy] = v
				q.append((x+dx, y+dy, v+is_sit[x+dx][y+dy]))
		
	print(ans)
	#s = input()	
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
a = list(map(int,input().split()))
ls = [0 for i in range(n*n)]
for i in range(n):
  for j in range(n):
    ls[i*n+j] = min(i,j,n-1-i,n-1-j)
ans = 0
st = set()
for i in a:
  x,y = divmod(i-1,n)
  ans += ls[i-1]
  st.add(i-1)
  q = deque([i-1])
  while q:
    j = q.popleft()
    px,py = divmod(j,n)
    for nx,ny in (px-1,py),(px+1,py),(px,py+1),(px,py-1):
      if 0 <= nx < n and 0 <= ny < n:
        k = nx*n+ny
        if j in st:
          if ls[j] < ls[k]:
            ls[k] = ls[j]
            q.append(k)
        elif ls[j]+1 < ls[j]:
          ls[k] = ls[j]+1
          q.append(k)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
a = list(map(int,input().split()))
ls = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
  for j in range(n):
    ls[i][j] = min(i,j,n-1-i,n-1-j)
ans = 0
st = set()
for i in a:
  x,y = divmod(i-1,n)
  ans += ls[x][y]
  st.add((x,y))
  q = deque([(x,y)])
  while q:
    px,py = q.popleft()
    for nx,ny in (px-1,py),(px+1,py),(px,py+1),(px,py-1):
      if 0 <= nx < n and 0 <= ny < n:
        if (nx,ny) in st:
          if ls[px][py] < ls[nx][ny]:
            ls[nx][ny] = ls[px][py]
            q.append((nx,ny))
        elif ls[px][py]+1 < ls[nx][ny]:
          ls[nx][ny] = ls[px][py]+1
          q.append((nx,ny))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
a = list(map(int,input().split()))
ls = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
  for j in range(n):
    ls[i][j] = min(i,j,n-1-i,n-1-j)
ans = 0
st = set()
for i in a:
  x,y = divmod(i-1,n)
  ans += ls[x][y]
  st.add((x,y))
  q = deque([(x,y)])
  while q:
    px,py = q.popleft()
    for nx,ny in (px-1,py),(px+1,py),(px,py+1),(px,py-1):
      if 0 <= nx < n and 0 <= ny < n:
        if (nx,ny) in st:
          if ls[px][py] < ls[nx][ny]:
            ls[nx][ny] = ls[px][py]
        elif ls[px][py]+1 < ls[nx][ny]:
          ls[nx][ny] = ls[px][py]+1
          q.append((nx,ny))
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 range(4):
            if i==2 and v%n==n-1: continue
            if i==1 and v%n==0: continue
            if i==0 and v < n: continue
            if i==3 and v+n >= N: continue
            nv = v+move[i]
            if 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:
# 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 range(4):
            if i==2 and v%n==n-1: continue
            if i==1 and v%n==0: continue
            nv = v+move[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:
import sys
input = sys.stdin.readline
n = int(input())
p = list(map(int,input().split()))

grid = [[i for i in range(1+j,n+j+1)]for j in range(0,n**2,n)]
kumi = [[-1]*(n**2)for i in range(n**2)]
ans = 0
for i in range(len(p)):
    x = p[i]//n if p[i]%n != 0 else p[i]//n-1
    y = (p[i]-1)%n
    mad1 = 0
    mad1list = []
    mad2 = 0
    mad2list = []
    mad3 = 0
    mad3list = []
    mad4 = 0
    mad4list = []
    dx = 1
    while x+dx <= n-1:
        if grid[x+dx][y] != '#':
            mad1 += 1
            mad1list.append(grid[x+dx][y])
        dx += 1

    dx = -1
    while x + dx >= 0:
        if grid[x + dx][y] != '#':
            mad2 += 1
            mad2list.append(grid[x + dx][y])
        dx -= 1
    dy = 1
    while y + dy <= n-1:
        if grid[x][y+dy] != '#':
            mad3 += 1
            mad3list.append(grid[x][y+dy])
        dy += 1
            
    dy = -1
    while y + dy >= 0:
        if grid[x][y+dy] != '#':
            mad4 += 1
            mad4list.append(grid[x][y+dy])
        dy -= 1
    if min(mad1,mad2,mad3,mad4) != 0:
        if mad1 == min(mad1,mad2,mad3,mad4):
            for m in mad1list:
                if kumi[grid[x][y]-1][m-1] != 0:
                    ans += 1
                    kumi[grid[x][y]-1][m-1] = 0
        elif mad2 == min(mad1,mad2,mad3,mad4):
            for m in mad2list:
                if kumi[grid[x][y]-1][m-1] != 0:
                    ans += 1
                    kumi[grid[x][y]-1][m-1] = 0
        elif mad3 == min(mad1,mad2,mad3,mad4):
            for m in mad3list:
                if kumi[grid[x][y]-1][m-1] != 0:
                    ans += 1
                    kumi[grid[x][y]-1][m-1] = 0
        else:
            for m in mad4list:
                if kumi[grid[x][y]-1][m-1] != 0:
                    ans += 1
                    kumi[grid[x][y]-1][m-1] = 0
        #madlist.append(p[i])
    grid[x][y] = '#'
print(ans)
#print(madlist)

Submission status: Wrong Answer

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

grid = [[i for i in range(1+j,n+j+1)]for j in range(0,n**2,n)]
kumi = [[-1]*(n**2)for i in range(n**2)]
madlist = []
ans = 0
for i in range(len(p)):
    x = p[i]//n if p[i]%n != 0 else p[i]//n-1
    y = (p[i]-1)%n
    mad1 = 0
    mad1list = []
    mad2 = 0
    mad2list = []
    mad3 = 0
    mad3list = []
    mad4 = 0
    mad4list = []
    dx = 1
    while x+dx <= n-1:
        if grid[x+dx][y] != '#':
            mad1 += 1
            mad1list.append(grid[x+dx][y])
        dx += 1

    dx = -1
    while x + dx >= 0:
        if grid[x + dx][y] != '#':
            mad2 += 1
            mad2list.append(grid[x + dx][y])
        dx -= 1
    dy = 1
    while y + dy <= n-1:
        if grid[x][y+dy] != '#':
            mad3 += 1
            mad3list.append(grid[x][y+dy])
        dy += 1
            
    dy = -1
    while y + dy >= 0:
        if grid[x][y+dy] != '#':
            mad4 += 1
            mad4list.append(grid[x][y+dy])
        dy -= 1
    if min(mad1,mad2,mad3,mad4) != 0:
        if mad1 == min(mad1,mad2,mad3,mad4):
            for m in mad1list:
                if kumi[grid[x][y]-1][m-1] != 0 and kumi[m-1][grid[x][y]-1] != 0:
                    ans += 1
                    kumi[grid[x][y]-1][m-1] = 0
                    kumi[m-1][grid[x][y]-1] = 0
        elif mad2 == min(mad1,mad2,mad3,mad4):
            for m in mad2list:
                if kumi[grid[x][y]-1][m-1] != 0 and kumi[m-1][grid[x][y]-1] != 0:
                    ans += 1
                    kumi[grid[x][y]-1][m-1] = 0
                    kumi[m-1][grid[x][y]-1] = 0
        elif mad3 == min(mad1,mad2,mad3,mad4):
            for m in mad3list:
                if kumi[grid[x][y]-1][m-1] != 0 and kumi[m-1][grid[x][y]-1] != 0:
                    ans += 1
                    kumi[grid[x][y]-1][m-1] = 0
                    kumi[m-1][grid[x][y]-1] = 0
        else:
            for m in mad4list:
                if kumi[grid[x][y]-1][m-1] != 0 and kumi[m-1][grid[x][y]-1] != 0:
                    ans += 1
                    kumi[grid[x][y]-1][m-1] = 0
                    kumi[m-1][grid[x][y]-1] = 0
        #madlist.append(p[i])
    grid[x][y] = '#'
print(ans)
#print(madlist)

Submission status: Wrong Answer

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

grid = [[i for i in range(1+j,n+j+1)]for j in range(0,n**2,n)]
end = []
madlist = []
ans = 0
for i in range(len(p)):
    x = p[i]//n if p[i]%n != 0 else p[i]//n-1
    y = (p[i]-1)%n
    mad1 = 0
    mad2 = 0
    mad3 = 0
    mad4 = 0
    dx = 1
    while x+dx <= n-1:
        if grid[x+dx][y] != '#':
            mad1 += 1
        dx += 1

    dx = -1
    while x + dx >= 0:
        if grid[x + dx][y] != '#':
            mad2 += 1
        dx -= 1
    dy = 1
    while y + dy <= n-1:
        if grid[x][y+dy] != '#':
            mad3 += 1
        dy += 1
            
    dy = -1
    while y + dy >= 0:
        if grid[x][y+dy] != '#':
            mad4 += 1
        dy -= 1
    if min(mad1,mad2,mad3,mad4) != 0:
        ans += min(mad1,mad2,mad3,mad4)
        #madlist.append(p[i])
    grid[x][y] = '#'
print(ans)
#print(madlist)

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()))
    costs = [-1 for _ in range(N**2)]
    exits = [0 for _ in range(N**2)]
    for i in range(N**2):
        q, mod = divmod(i, N)
        up, down, left, right = q, N-q-1, mod, N-mod-1
        costs[i] = min(up, down, left, right)
    ans = 0
    for i in range(N**2):
        current = P[i]-1
        ans += costs[current]
        exits[current] = 1
        dist = [-1 for _ in range(N**2)]
        que = deque([])
        dist[current] = 0
        que.append(current)
        while len(que) != 0:
            v = que.popleft()
            arround = []
            for nv in [v-1, v+1, v+N, v-N]:
                if 0 < nv < N**2 and costs[nv] > 0:
                    if exits[v] == 1 or dist[nv] == 1:
                        arround.append(nv)
            for nv in arround:
                if dist[nv] != -1:continue
                dist[nv] += 1
                costs[nv] = min(costs[v], costs[nv])
                que.append(nv)
    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

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)

def kousin(v,nv):
    if dist[nv] > dist[v] + iru[v]:
        q.append(nv)
        dist[nv] = dist[v] + iru[v]


#ans = [0]*N
ans = 0
iru = [1]*N
q = []
for pi in p:
    pi -= 1

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

    q.append(pi)
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        if v%n != n-1:
            kousin(v,v+1)
        if v%n:
            kousin(v,v-1)
        if v >= n:
            kousin(v,v-n)
        if v+n < N:
            kousin(v,v+n)


                    
    #print(dist)        

print(ans)






if n==3: print(1)

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
q = []
for pi in p:
    pi -= 1

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

    q.append(pi)
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        if v%n != n-1:
            nv = v+1
            if dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        if v%n:
            nv = v-1
            if dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        if v >= n:
            nv = v-n
            if dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        if v+n < N:
            nv = v+n
            if 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:
# 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
q = []
qa = q.append
for pi in p:
    pi -= 1

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

    qa(pi)
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        for i in [-n,-1,1,n]:
            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]:
                qa(nv)
                dist[nv] = dist[v] + iru[v]
        
                    
    #print(dist)        

print(ans)






if n==3: print(1)

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
q = []
for pi in p:
    pi -= 1

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

    q.append(pi)
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        for i in [-n,-1,1,n]:
            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:
import numpy as np
N = int(input())
P = list(map(int, input().split()))
p = np.ones((N, N))
ans = 0
for Pi in P:
    x = (Pi - 1) % N
    y = (Pi - 1) // N
    p[x, y] = 0
    left = sum(p[x, 0:y])
    right = sum(p[x, y:])
    front = sum(p[0:x, y])
    back = sum(p[x:, y])
    ans += min(left, right, front, back)
print(int(ans))

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()

    nx = [[0] * N for _ in range(N)]
    ny = [[0] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            nx[j][i] = j+1
            ny[i][j] = j+1
    ans = 0
    for a in P:
        x = (a-1) % N
        y = (a-1) // N
        if x == 0 or x == N-1 or y == 0 or y == N-1:
            min_cnt = 0
        else:
            min_cnt = min(nx[x-1][y],nx[-1][y]-nx[x][y],ny[x][y-1],ny[x][-1]-ny[x][y])
            for i in range(1,y):
                min_cnt = min(min_cnt,ny[x][y-1]-ny[x][i-1] + min(nx[x-1][i],nx[-1][i]-nx[x][i]))
            for i in range(y+1,N-1):
                min_cnt = min(min_cnt,ny[x][i]-ny[x][y] + min(nx[x-1][i],nx[-1][i]-nx[x][i]))

            for i in range(1,x):
                min_cnt = min(min_cnt,nx[x-1][y]-nx[i-1][y] + min(ny[i][y-1],ny[i][-1]-ny[i][x]))
            for i in range(x+1,N-1):
                min_cnt = min(min_cnt,nx[i][y]-nx[x][y] + min(ny[i][y-1],ny[i][-1]-ny[i][x]))

        ans += min_cnt

        for i in range(x,N):
            nx[i][y] -= 1
        for i in range(y,N):
            ny[x][i] -= 1
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
S = {}

def dsMakeSet(ds, x):
    ds[x] = x


def dsFind(ds, x):
    if ds[x] == x:
        return x

    x0 = x
    while ds[x] != x:
        x = ds[x]

    ds[x0] = x
    return x


def dsUnion(ds, x, y):
    xRoot = dsFind(ds, x)
    yRoot = dsFind(ds, y)
    
    if xRoot != yRoot:
        ds[yRoot] = xRoot
        S[xRoot] = tuple([min(xy[0], xy[1]) for xy in zip(S[xRoot], S[yRoot])])
        return True

    return False



N = int(input())
P = list(map(int, input().split()))
ds = {}
ans = 0

for p in P:
    row = (p-1)//N
    col = (p-1)%N
    key = (row, col)

    if not(key in ds):
        dsMakeSet(ds, key)
        S[key] = (row, col, N-row-1, N-col-1)
        
        if (row-1, col) in ds:
            dsUnion(ds, key, (row-1, col))
            
        if (row+1, col) in ds:
            dsUnion(ds, key, (row+1, col))
            
        if (row, col-1) in ds:
            dsUnion(ds, key, (row, col-1))
            
        if (row, col+1) in ds:
            dsUnion(ds, key, (row, col+1))
            
        root = dsFind(ds, key)
        ans += min(S[root])

print(ans)

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
        for i in range(4):
            nx = x+dx[i]
            ny = y+dy[i]
            if 0 <= nx < n and 0 <= ny < n:
                d[x][y] = min(d[x][y],d[nx][ny]+check[nx][ny])
        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]+check[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:
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
        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:
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 = d[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])
        d[x][y] = min(d[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:
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])
        d[x][y] = min(d[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()