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: Time Limit Exceeded

Solution code:
import heapq

INF = 10**3
n = int(input())
A = list(map(int,input().split()))

F = [[True]*n for _ in range(n)]
V = [[False]*n for _ in range(n)]

def escape(F,ys,xs,n):
  if xs==0 or xs==n-1 or ys==0 or ys==n-1 or V[ys][xs]:    
    return 0  
    
  G = [[INF]*n for _ in range(n)]
  G[ys][xs] = 0
  
  que = [(0,ys,xs)] 
  while len(que)>0:
    c,y,x = heapq.heappop(que)    
    if x==0 or x==n-1 or y==0 or y==n-1 or V[y][x]:      
      return c
    
    for dy,dx in ((0,1),(1,0),(0,-1),(-1,0)):
      nx = dx+x
      ny = dy+y
      
      if G[ny][nx] > G[y][x]:
        G[ny][nx] = G[y][x] + F[ny][nx]        
        heapq.heappush(que,(G[ny][nx],ny,nx))        
    
ans = 0
for a in A:
  y = (a-1) //n
  x = (a-1) % n
  F[y][x] = False
  
  if x==0 or x==n-1 or y==0 or y==n-1:
    V[y][x] = True
  else:
    for dy,dx in ((0,1),(1,0),(0,-1),(-1,0)):
      nx = dx+x
      ny = dy+y
      if V[ny][nx] == True:
        V[y][x] = True
                    
  c = escape(F,y,x,n)  
      
  ans += c
  
print(ans)

Submission status: Time Limit Exceeded

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


import logging

logging.basicConfig(level=logging.DEBUG)

def update_map(x,y, zaseki_map, tyakuseki_map):

    logging.debug("{0},{1}".format(x,y))
    
    if x - 1 >= 0:
        if tyakuseki_map[x][y] + zaseki_map[x][y] < zaseki_map[x-1][y]:
            zaseki_map[x-1][y] = tyakuseki_map[x][y] + zaseki_map[x][y]
            update_map(x-1, y, zaseki_map, tyakuseki_map)

    if x + 1 < len(zaseki_map):
        if tyakuseki_map[x][y] + zaseki_map[x][y] < zaseki_map[x+1][y]:
            zaseki_map[x+1][y] = tyakuseki_map[x][y] + zaseki_map[x][y]
            update_map(x+1, y, zaseki_map, tyakuseki_map)
    
       
    if y - 1 >= 0:
        if tyakuseki_map[x][y] + zaseki_map[x][y] < zaseki_map[x][y-1]:
            zaseki_map[x][y-1] = tyakuseki_map[x][y] + zaseki_map[x][y]
            update_map(x, y-1, zaseki_map, tyakuseki_map)

    if y + 1 < len(zaseki_map):
        if tyakuseki_map[x][y] + zaseki_map[x][y] < zaseki_map[x][y+1]:
            zaseki_map[x][y+1] = tyakuseki_map[x][y] + zaseki_map[x][y]
            update_map(x, y+1, zaseki_map, tyakuseki_map)
    
    
    
def riseki(p, zaseki_map, tyakuseki_map):
    
    x, y = ((p-1) % len(zaseki_map), int((p-1) / len(zaseki_map)))
    result = zaseki_map[x][y]
    tyakuseki_map[x][y] = 0    
    update_map(x,y, zaseki_map, tyakuseki_map)

    return result


if __name__ == "__main__":
    N = int(input())
    P_list = list(map(int, input().split()))
    
    logging.debug("N:{0}".format(N))
    logging.debug("P:{0}".format(P_list))
        
    
    center = int(N/2)
    zaseki_map = [[0]*N for _ in range(N)]
    tyakuseki_map = [[1]*N for _ in range(N)]
    
    logging.debug(center)
    
    for i in range(N):
        for j in range(N):
            a = i if i < center else (N-1) - i
            b = j if j < center else (N-1) - j
            zaseki_map[i][j] = min(a, b)
    
    for i in zaseki_map:
        logging.debug(i)
        
    
    count = 0
    for p in P_list:
        logging.debug("-----------")
        count += riseki(p, zaseki_map, tyakuseki_map)
        for i in zaseki_map:
            logging.debug(i)
    
    print(count)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
import itertools


class Cell(object):

  def __init__(self, x, y):
    self.x = x
    self.y = y
    self.value = None
    self.exist = 1
    self.neighbors = set()

  def __hash__(self):
    return self.x + self.y * 500

  def __eq__(self, obj):
    return self.x == obj.x and self.y == obj.y


def main():
  N = int(input())
  cells = [[Cell(x, y) for x in range(N)] for y in range(N)]
  queue = collections.deque()
  count = 0

  for x, y in itertools.product(range(N), repeat=2):
    c = cells[y][x]

    if x == 0:
      c.value = 0
    else:
      c.neighbors.add(cells[y][x - 1])

    if x == N - 1:
      c.value = 0
    else:
      c.neighbors.add(cells[y][x + 1])

    if y == 0:
      c.value = 0
    else:
      c.neighbors.add(cells[y - 1][x])

    if y == N - 1:
      c.value = 0
    else:
      c.neighbors.add(cells[y + 1][x])

    if c.value == 0:
      queue.append(c)

  while len(queue) != 0:
    c = queue.popleft()

    for n in c.neighbors:
      if n.value is None:
        n.value = c.value + 1
        queue.append(n)

  for i in map(int, input().split()):
    x, y = divmod(i - 1, N)
    count += cells[y][x].value
    cell = cells[y][x]

    cell.value -= 1
    cell.exist = 0

    for n in list(cell.neighbors):
      if n.exist != 0:
        continue

      cell.neighbors |= n.neighbors
      cells[n.y][n.x] = cell

    queue = collections.deque()
    queue.append(cells[y][x])

    while len(queue) != 0:
      c = queue.popleft()

      for n in c.neighbors:
        if n.value > c.value + n.exist:
          n.value = c.value + n.exist
          queue.append(n)

  print(count)


if __name__ == '__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
from numba import jit

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

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

#+++++

@jit
def gg(nn, x, y, n, is_sit):
	q = deque()
	q.append(1000*x+y)
	cl = set()
	cl.add(x*1000+y)
	while q:
		v = q.popleft()
		x,y = v//1000, v %1000
		nn[x][y] -= 1
		k = nn[x][y]
		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
			if nn[x+dx][y + dy] <= k + is_sit[x+dx][y+dy]:
				continue
			if (x+dx)*1000+(y+dy) in cl:
				continue
			q.append((x+dx)*1000+ (y+dy))
			cl.add((x+dx)*1000 + (y+dy))
		#print('yyyyyy')
		#for l in nn:
		#	print(l)

def main():
	n = int(input())
	nn = [[(n+1)//2] * n for _ in range(n)]
	is_sit = [[1] * n for _ in range(n)]
	for i in range(n):
		for j in range(n):
			nn[i][j] = min(i+1,j+1,n-i,n-j)
	#for l in nn:
	#	print(l)
	
	#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] = 0
		gg(nn, x, y, n, is_sit)
		
	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:
		pass
		input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Time Limit Exceeded

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

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

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

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

from collections import deque

N = int(input())

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

Rab = []
for _ in range(0,N):
    Rab.append([1]*N)

CheckRab = []
for _ in range(0,N):
    CheckRab.append([0]*N)


# スタート地点から何ステップで到着できるかを計算するため
StepNum = 0

cnt = 0

for Pi in P:

    if Rab == CheckRab:
        break

    # Piの客が訪れた場所をマークするための配列
    # X = まだ   O = 一度訪れた
    visit = []
    for _ in range(0,N):
        visit.append(list("X"*N))
    visit[(Pi-1)//N][(Pi-1)%N] = "O"

    # その場所を通る場合において，嫌われる客の最小数
    HateNum = [] 
    for _ in range(0,N):
        HateNum.append([0]*N)

    # Pi の客のスタート
    d = deque([[(Pi-1)//N, (Pi-1)%N]])
    
    while d:

        now = d.popleft()

        # 場外に出れるならOK
        if now[0]-1 == 0:
            if Rab[now[0]-1][now[1]] == 0:
                Rab[(Pi-1)//N][(Pi-1)%N] = 0
                break
        if now[0]+1 == N-1:
            if Rab[now[0]+1][now[1]] == 0:
                Rab[(Pi-1)//N][(Pi-1)%N] = 0
                break
        if now[1]-1 == 0:
            if Rab[now[0]][now[1]-1] == 0:
                Rab[(Pi-1)//N][(Pi-1)%N] = 0
                break
        if now[1]+1 == N-1:
            if Rab[now[0]][now[1]+1] == 0:
                Rab[(Pi-1)//N][(Pi-1)%N] = 0
                break

        # 場外に出れるならOK
        if now[0]-1 == -1:
            Rab[(Pi-1)//N][(Pi-1)%N] = 0
            break
        if now[0]+1 == N:
            Rab[(Pi-1)//N][(Pi-1)%N] = 0
            break
        if now[1]-1 == -1:
            Rab[(Pi-1)//N][(Pi-1)%N] = 0
            break
        if now[1]+1 == N:
            Rab[(Pi-1)//N][(Pi-1)%N] = 0
            break
        

        # now マスの左のマスが行ってない場合
        if visit[now[0]-1][now[1]] == "X":
            # もしその場所が誰か座ってル場合
            if Rab[now[0]-1][now[1]] == 1:
                visit[now[0]-1][now[1]] = "O" # その場所を行ったことにして
                HateNum[now[0]-1][now[1]] = HateNum[now[0]][now[1]]+1 # その場所のHateNumを今の場所のひとつ上に
                d.append([now[0]-1,now[1]]) # その場所を次のHateNumの順番で検するように右に追加する
            # もしその場所が誰も座っていない場合
            if Rab[now[0]-1][now[1]] == 0:
                visit[now[0]-1][now[1]] = "O" # その場所を行ったことにして
                HateNum[now[0]-1][now[1]] = HateNum[now[0]][now[1]] # その場所のHateNumを今の場所と同じにして
                d.appendleft([now[0]-1,now[1]]) # その場所をすぐに調べるように左に追加する．

        # now マスの右のマスが行ってない場合
        if visit[now[0]+1][now[1]] == "X":
            # もしその場所が誰か座ってル場合
            if Rab[now[0]+1][now[1]] == 1:
                visit[now[0]+1][now[1]] = "O" # その場所を行ったことにして
                HateNum[now[0]+1][now[1]] = HateNum[now[0]][now[1]]+1 # その場所のHateNumを今の場所のひとつ上に
                d.append([now[0]+1,now[1]]) # その場所を次のHateNumの順番で検するように右に追加する
            # もしその場所が誰も座っていない場合
            if Rab[now[0]+1][now[1]] == 0:
                visit[now[0]+1][now[1]] = "O" # その場所を行ったことにして
                HateNum[now[0]+1][now[1]] = HateNum[now[0]][now[1]] # その場所のHateNumを今の場所と同じにして
                d.appendleft([now[0]+1,now[1]]) # その場所をすぐに調べるように左に追加する．

        # now マスの上のマスが行ってない場合
        if visit[now[0]][now[1]-1] == "X":
            # もしその場所が誰か座ってル場合
            if Rab[now[0]][now[1]-1] == 1:
                visit[now[0]][now[1]-1] = "O" # その場所を行ったことにして
                HateNum[now[0]][now[1]-1] = HateNum[now[0]][now[1]]+1 # その場所のHateNumを今の場所のひとつ上に
                d.append([now[0],now[1]-1]) # その場所を次のHateNumの順番で検するように右に追加する
            # もしその場所が誰も座っていない場合
            if Rab[now[0]][now[1]-1] == 0:
                visit[now[0]][now[1]-1] = "O" # その場所を行ったことにして
                HateNum[now[0]][now[1]-1] = HateNum[now[0]][now[1]] # その場所のHateNumを今の場所と同じにして
                d.appendleft([now[0],now[1]-1]) # その場所をすぐに調べるように左に追加する．

        # now マスの下のマスが行ってない場合
        if visit[now[0]][now[1]+1] == "X":
            # もしその場所が誰か座ってル場合
            if Rab[now[0]][now[1]+1] == 1:
                visit[now[0]][now[1]+1] = "O" # その場所を行ったことにして
                HateNum[now[0]][now[1]+1] = HateNum[now[0]][now[1]]+1 # その場所のHateNumを今の場所のひとつ上に
                d.append([now[0],now[1]+1]) # その場所を次のHateNumの順番で検するように右に追加する
            # もしその場所が誰も座っていない場合
            if Rab[now[0]][now[1]+1] == 0:
                visit[now[0]][now[1]+1] = "O" # その場所を行ったことにして
                HateNum[now[0]][now[1]+1] = HateNum[now[0]][now[1]] # その場所のHateNumを今の場所と同じにして
                d.appendleft([now[0],now[1]+1]) # その場所をすぐに調べるように左に追加する．

    cnt += HateNum[now[0]][now[1]]

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import heapq

INF = 10**3
n = int(input())
A = list(map(int,input().split()))

F = [[True]*n for _ in range(n)]
V = [[False]*n for _ in range(n)]

def escape(F,ys,xs,n):
  if xs==0 or xs==n-1 or ys==0 or ys==n-1 or V[ys][xs]:    
    return 0  
    
  G = [[INF]*n for _ in range(n)]
  G[ys][xs] = 0
  
  que = [(0,ys,xs)] 
  while len(que)>0:
    c,y,x = heapq.heappop(que)    
    if x==0 or x==n-1 or y==0 or y==n-1 or V[ys][xs]:      
      return c
    
    for dy,dx in ((0,1),(1,0),(0,-1),(-1,0)):
      nx = dx+x
      ny = dy+y
      
      if G[ny][nx] > G[y][x]:
        G[ny][nx] = G[y][x] + F[ny][nx]        
        heapq.heappush(que,(G[ny][nx],ny,nx))        
    
ans = 0
for a in A:
  y = (a-1) //n
  x = (a-1) % n
  F[y][x] = False
  
  if x==0 or x==n-1 or y==0 or y==n-1:
    V[y][x] = True
  else:
    for dy,dx in ((0,1),(1,0),(0,-1),(-1,0)):
      nx = dx+x
      ny = dy+y
      if V[ny][nx] == True:
        V[y][x] = True
                    
  c = escape(F,y,x,n)  
      
  ans += c
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
Ps = list(map(lambda x: int(x), input().split()))

inf = 10**10
from collections import deque
import heapq

dirc = ((0, -1), (1, 0), (0, 1), (-1, 0))
def djikstra(s):
    checked = set()
    queue = [(0, s)]
    heapq.heapify(queue)
    while queue:
        c, (y, x) = heapq.heappop(queue)
        if (y, x) in checked:
            continue
        checked.add((y, x))
        if y<1 or y>=N+1 or x<1 or x>=N+1:
            return c//inf
        for dy, dx in dirc:
            ny, nx = y+dy, x+dx
            if (ny, nx) not in checked:
                if (ny, nx) in near:
                    return c//inf
                heapq.heappush(queue, (c+cost[ny][nx], (ny, nx)))
        
cost = [[0]+[inf]*N+[0] if i!=0 and i!=N+1 else [0]*(N+2) for i in range(N+2)]
ans = 0
near = set()
for i in range(N**2):
    p = Ps[i]-1
    y = p//N+1
    x = p%N+1
    dji = 1
    for dy, dx in dirc:
        ny, nx = y+dy, x+dx
        if (ny, nx) in near:
            dji = 0
            break
    if dji:
        dji = djikstra((y, x))
    if dji==0:
        near.add((y, x))
    ans += dji
    cost[y][x] = 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:

import sys
sys.setrecursionlimit(10000)
input = sys.stdin.readline


def ij_to_n(i,j,W):
    return i*W+j

def n_to_ij(n,W):
    return (n//W,n%W)


def n_to_ij_oneoffset(n,W):
    #n+=1
    return (1+(n-1)//W,1+(n-1)%W)


def acinput():
    return list(map(int, input().split(" ")))
       

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


N=int(input())
H,W=N,N


""" field = [[-1]*(N+2)]

for i in range(N):
    tmp=[-1]
    
    inputv=[]
    tmp.extend([0]*N)
    tmp.append(-1)           
    field.append(tmp)
    
for i in range(1,N+1):
    for j in range(1,N+1):
        field[i][j]=N*(i-1)+j
        
field.append([-1]*(N+2)) """

#dp=np.full([H+2,W+2],300)
#state=np.full([H+2,W+2],1)

def array(size,init):
    return [[init for j in range(size[1])] for i in range(size[0])]

dp=array([H+2,W+2],300)
state=array([H+2,W+2],1)

def propagete(x):
    global directions,state
    v=dp[x[0]][x[1]]+state[x[0]][x[1]]
    #print(x,v)
    nd=[0,0]
    for sd in directions:
        nd[0]=x[0]+sd[0]
        nd[1]=x[1]+sd[1]
        
        if dp[nd[0]][nd[1]]>v:
            dp[nd[0]][nd[1]]=v
            propagete(nd)

import heapq        
def propagete2(x):
    
    global direactions,state
    
    v=dp[x[0]][x[1]]
    queue=[(-v,x)]
    nd=[0,0]
    while True:
        v,r=heapq.heappop(queue)
        v-=state[r[0]][r[1]]
        
        for sd in directions:
            nd[0]=r[0]+sd[0]
            nd[1]=r[1]+sd[1]
            #import numpy as np
            #print(np.array(dp),v,nd)
            #print(v)
            #print(state)
            if dp[nd[0]][nd[1]]>-v:
                dp[nd[0]][nd[1]]=-v
                nd2=nd[:]
                heapq.heappush(queue,(v,nd2))
        
        if len(queue)==0:
            return

for i in range(1,N+1):
    for j in range(1,N+1):
        dp[i][j]=min(i-1,H-i,j-1,W-j)
        
P=acinput()  


tmp=[0]*(N+2)
dp[1]=tmp
dp[H]=tmp

for j in range(H+2):
    dp[j][1]=0
    dp[j][W]=0
    
    dp[j][0]=0
    dp[j][W+1]=0

dp[0]=tmp
dp[H+1]=tmp


#print(dp)
res=0
for p in P:
    r=n_to_ij_oneoffset(p,N)
    #print(p,r)
    #print(dp[r[0],r[1]])
    res+=dp[r[0]][r[1]]
    state[r[0]][r[1]]=0
    propagete2(r)
    
print(res)

#print(dp)

Submission status: Time Limit Exceeded

Solution code:
from random import shuffle
N = 500
P = list(range(N*N))#[int(c)-1 for c in input().split()]
shuffle(P)
import numba
import numpy as np
#N = int(input())
#P = [int(c)-1 for c in input().split()]
Mat = [[min(y, N-1-y, x, N-1-x) for y in range(N)] for x in range(N)]
Mat = np.array(Mat)
Removed = np.zeros((N, N), dtype=np.bool)
Dy, Dx = [1,0,-1,0], [0,1,0,-1]
@numba.jit()
def proc():
    ans = 0
    closed = np.zeros((N,N), dtype=np.bool)
    for i in range(N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y][x]
        #print(p, Mat[y][x])
        Removed[y][x] = True
        #Mat[y][x] -= 1
        st = [(y, x)]
        clsd = [(y, x)]
        closed[y][x] = True
        while st:
            vy, vx = st.pop()
            vr = Removed[vy][vx]
            val = Mat[vy][vx]
            for dy, dx in zip(Dy, Dx):
                uy = vy + dy
                ux = vx + dx
                if not (0<=uy<N and 0<=ux<N):
                    continue
                if closed[uy][ux]:
                    continue
                ur = Removed[uy][ux]
                if vr:
                    if Mat[uy][ux] >= val+1:
                        Mat[uy][ux] = val
                        st.append((uy, ux))
                else:
                    if Mat[uy][ux] >= val+2:
                        Mat[uy][ux] = val+1
                        st.append((uy, ux))
        for y, x in clsd:
            closed[y][x] = False
    # for m in Mat:
    #     print(m)
    print(ans)
proc()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
#from numba import jit

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

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

#+++++

#@jit
def gg(nn, x, y, n, is_sit):
	q = deque()
	q.append(1000*x+y)
	cl = set()
	cl.add(x*1000+y)
	while q:
		v = q.popleft()
		x,y = v//1000, v %1000
		nn[x][y] -= 1
		k = nn[x][y]
		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
			if nn[x+dx][y + dy] <= k + is_sit[x+dx][y+dy]:
				continue
			if (x+dx)*1000+(y+dy) in cl:
				continue
			q.append((x+dx)*1000+ (y+dy))
			cl.add((x+dx)*1000 + (y+dy))
		#print('yyyyyy')
		#for l in nn:
		#	print(l)

def main():
	n = int(input())
	nn = [[(n+1)//2] * n for _ in range(n)]
	is_sit = [[1] * n for _ in range(n)]
	for i in range(n):
		for j in range(n):
			nn[i][j] = min(i+1,j+1,n-i,n-j)
	#for l in nn:
	#	print(l)
	
	#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] = 0
		gg(nn, x, y, n, is_sit)
		
	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:
		pass
		input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
Ps = list(map(lambda x: int(x), input().split()))

inf = 10**10
from collections import deque
import heapq

dirc = ((0, -1), (1, 0), (0, 1), (-1, 0))
def djikstra(s):
    checked = set()
    queue = [(0, s)]
    heapq.heapify(queue)
    while queue:
        c, (y, x) = heapq.heappop(queue)
        if (y, x) in checked:
            continue
        checked.add((y, x))
        if y<1 or y>=N+1 or x<1 or x>=N+1:
            return c//inf
        for dy, dx in dirc:
            ny, nx = y+dy, x+dx
            if (ny, nx) not in checked:
                if near[ny][nx]==0:
                    return c//inf
                heapq.heappush(queue, (c+cost[ny][nx], (ny, nx)))
        
cost = [[0]+[inf]*N+[0] if i!=0 and i!=N+1 else [0]*(N+2) for i in range(N+2)]
ans = 0
near = [[-1]*(N+2) for _ in range(N+2)]
for i in range(N**2):
    p = Ps[i]-1
    y = p//N+1
    x = p%N+1
    dji = 1
    for dy, dx in dirc:
        ny, nx = y+dy, x+dx
        if near[ny][nx]==0:
            dji = 0
            break
    if dji:
        dji = djikstra((y, x))
    near[y][x] = dji
    ans += dji
    cost[y][x] = 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq

INF = 10**3
n = int(input())
A = list(map(int,input().split()))

F = [[True]*n for _ in range(n)]
V = [[False]*n for _ in range(n)]

def escape(F,ys,xs,n):
  if xs==0 or xs==n-1 or ys==0 or ys==n-1:    
    return 0
  if V[ys][xs]:    
    return 0
    
  G = [[INF]*n for _ in range(n)]
  G[ys][xs] = 0
  
  que = [(0,ys,xs)] 
  while len(que)>0:
    c,y,x = heapq.heappop(que)    
    if x==0 or x==n-1 or y==0 or y==n-1:      
      return c
    
    for dy,dx in ((0,1),(1,0),(0,-1),(-1,0)):
      nx = dx+x
      ny = dy+y
      
      if G[ny][nx] > G[y][x]:
        G[ny][nx] = G[y][x] + F[ny][nx]        
        heapq.heappush(que,(G[ny][nx],ny,nx))        
    
ans = 0
for a in A:
  y = (a-1) //n
  x = (a-1) % n
  F[y][x] = False
  
  if x==0 or x==n-1 or y==0 or y==n-1:
    V[y][x] = True
  else:
    for dy,dx in ((0,1),(1,0),(0,-1),(-1,0)):
      nx = dx+x
      ny = dy+y
      if V[ny][nx] == True:
        V[y][x] = True
                    
  c = escape(F,y,x,n)  
      
  ans += c
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python
from collections import deque

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

    seat = [[-1 for i in range(n+2)] for j in range(n+2)]
    yet = [[0 for i in range(n+2)] for j in range(n+2)]
    for i in range(1, n+1):
        for j in range(1, n+1):
            m = min(i-1, j-1, n-i, n-j)
            seat[i][j] = m
            yet[i][j] = 1

    cnt = 0
    direct = [[-1,0], [1,0], [0,-1], [0,1]]
    for q in p:
        x, y = divmod(q-1, n)
        x += 1
        y += 1
        cnt += seat[x][y]
        seat[x][y] -= 1
        yet[x][y] = 0
        que = deque([[x, y]])

        while que:
            x0, y0 = que.pop()
            h = seat[x0][y0]
            for d in direct:
                x1, y1 = x0 + d[0], y0 + d[1]
                if seat[x1][y1] > h + yet[x1][y1]:
                    seat[x1][y1] = h + yet[x1][y1]
                    que.append([x1, y1])

    print(cnt)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
from collections import deque

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
P = lr()
dp = [[min(i, N-1-i)] * N for i in range(N)]
people = [[True] * N for i in range(N)]
for j in range(N):
    x = min(j, N-1-j)
    for i in range(N):
        dp[i][j] = min(dp[i][j], x)

answer = 0
for p in P:
    p -= 1
    i = p // N
    j = p % N
    answer += dp[i][j]
    dp[i][j] -= 1
    people[i][j] = False
    used = set()
    def bfs(sy, sx):
        que = deque([(sy, sx)])
        popleft = que.popleft; append = que.append
        while que:
            y, x = popleft()
            if (y, x) in used:
                continue
            used.add((y, x))
            cur = dp[y][x]
            if cur == -1 and not people[y][x]:
                people[y][x] = True
            for dy, dx in zip([0, 1, 0, -1], [1, 0, -1, 0]):
                ny = y + dy
                nx = x + dx
                if 0 <= ny < N and 0 <= nx < N:
                    if dp[ny][nx] > cur + 1:
                        dp[ny][nx] = cur + 1
                        if not people[ny][nx]:
                            dp[ny][nx] = cur
                        append((ny, nx))
                    elif dp[ny][nx] > cur and (not people[ny][nx]):
                        # 人がいない時
                        dp[ny][nx] = cur
                        append((ny, nx))
    bfs(i, j)

print(answer)

Submission status: Time Limit Exceeded

Solution code:
import sys, bisect, math, itertools, heapq, collections
from operator import itemgetter
# a.sort(key=itemgetter(i)) # i番目要素でsort
from functools import lru_cache
# @lru_cache(maxsize=None)
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
INF = float('inf')
mod = 10**9 + 7
eps = 10**-7


def inp():
    '''
    一つの整数
    '''
    return int(input())


def inpl():
    '''
    一行に複数の整数
    '''
    return list(map(int, input().split()))


def str_inp():
    '''
    文字列をリストとして読み込む
    '''
    return list(input()[:-1])


n = inp()
p = inpl()
# with open("./temp_input.txt", "r") as f:
#     l = f.readlines()
#     n = int(l[0])
#     p = list(map(int, l[1].split()))
dic = collections.defaultdict(set)
for i in range(n**2):
    chair = i + 1
    if chair > n:
        dic[chair].add(chair - n)
    else:
        dic[chair].add(0)
    if (chair - 1) % n > 0:
        dic[chair].add(chair - 1)
    else:
        dic[chair].add(0)
    if (chair) % n > 0:
        dic[chair].add(chair + 1)
    else:
        dic[chair].add(0)
    if (chair) <= n * (n - 1):
        dic[chair].add(chair + n)
    else:
        dic[chair].add(0)
ans = 0
exited = set()
exited.add(0)
for i in range(n**2):
    chair = p[i]
    queue = [(0, i) for i in dic[chair]]
    visited = set()
    if 0 in dic[chair]:
        while len(queue):
            hate, now_chair = heapq.heappop(queue)
            if now_chair in visited:
                continue
            if (0 not in dic[now_chair]):
                dic[now_chair].add(0)
                if (now_chair in exited):
                    for j in dic[now_chair]:
                        heapq.heappush(queue, (hate, j))
            visited.add(now_chair)
    else:
        while True:
            hate, now_chair = heapq.heappop(queue)
            if now_chair in visited:
                continue
            if now_chair == 0:
                ans += hate
                break
            elif now_chair not in exited:
                hate += 1

            for j in dic[now_chair]:
                heapq.heappush(queue, (hate, j))
            visited.add(now_chair)
        exited.add(chair)
    # print(chair, ans)
# print(dic)
print(ans)

Submission status: Time Limit Exceeded

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 i in range(N):
    a = i//n
    b = i%n
    dist[i] = min(a,n-1-a,b,n-1-b)

#print(dist)


#ans = [0]*N
ans = 0
iru = [1]*N
from collections import deque
for I,pi in enumerate(p):
    pi -= 1

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

    q = deque([pi])
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        d = dist[v]
        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 nv < 0 or nv >= N: continue
            
            if dist[nv] > d + iru[v]:
                q.append(nv)
                dist[nv] = d + iru[v]
        
                    
    #print(dist)        

print(ans)