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 sys

sys.setrecursionlimit(25000)


def _i(): return int(sys.stdin.readline().strip())


def _ia(): return map(int, sys.stdin.readline().strip().split())


visited = {}


def update(n, cost, idx):
    global visited
    ci = cost[idx] + visited.get(idx, 1)

    # left
    if idx % n != 0:
        idx_ = idx - 1
        if cost[idx_] > ci:
            cost[idx_] = ci
            update(n, cost, idx_)

    # right
    idx_ = idx + 1
    if idx_ % n != 0:
        if cost[idx_] > ci:
            cost[idx_] = ci
            update(n, cost, idx_)

    # front
    idx_ = idx - n
    if idx_ >= 0:
        if cost[idx_] > ci:
            cost[idx_] = ci
            update(n, cost, idx_)

    # back
    idx_ = idx + n
    if idx_ // n < n:
        if cost[idx_] > ci:
            cost[idx_] = ci
            update(n, cost, idx_)


def main():
    global visited

    n = _i()
    p = list(map(lambda x: int(x)-1, _ia()))
    cost = [min(i//n, i % n, n-1-(i % n), n-1-i//n) for i in range(n**2)]

    tot = 0
    for pi in p:
        visited[pi] = 0
        ci = cost[pi]
        tot += ci
        update(n, cost, pi)

    return tot


if __name__ == "__main__":
    print(main())

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
from math import floor, sqrt, factorial, hypot, log  # log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter, defaultdict, deque
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint


def ceil(a, b): return (a + b - 1) // b


inf = float('inf')
mod = 10 ** 9 + 7


def pprint(*A):
    for a in A:     print(*a, sep='\n')


def INT_(n): return int(n) - 1


def MI(): return map(int, input().split())


def MF(): return map(float, input().split())


def MI_(): return map(INT_, input().split())


def LI(): return list(MI())


def LI_(): return [int(x) - 1 for x in input().split()]


def LF(): return list(MF())


def LIN(n: int): return [I() for _ in range(n)]


def LLIN(n: int): return [LI() for _ in range(n)]


def LLIN_(n: int): return [LI_() for _ in range(n)]


def LLI(): return [list(map(int, l.split())) for l in input()]


def I(): return int(input())


def F(): return float(input())


def ST(): return input().replace('\n', '')


def main():
    N = I()
    P = MI()
    emp = [[1] * (N + 1) for _ in range(N + 1)]
    dp = [[inf] * (N + 1) for _ in range(N + 1)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    for x in range(1, N + 1):
        for y in range(1, N + 1):
            ax = min(x - 1, N - x)
            ay = min(y - 1, N - y)
            dp[x][y] = min(ax, ay)
    ans = 0
    for i in P:
        y = (i % N)
        x = (i // N) + 1
        if y == 0:
            y += N
            x -= 1
        ans += dp[x][y]
        emp[x][y] = 0
        q = {(x, y)}
        while q:
            now = q.pop()
            for j in range(len(dx)):
                nx = now[0] + dx[j]
                ny = now[1] + dy[j]
                if 1 <= nx <= N and 1 <= ny <= N and dp[nx][ny] == dp[now[0]][now[1]] + 1 + emp[now[0]][now[1]]:
                    dp[nx][ny] -= 1
                    q.add((nx, ny))
    print(ans)


if __name__ == '__main__':
    main()

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
for I,pi in enumerate(p):
    pi -= 1

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

    q = [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)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
from math import floor, sqrt, factorial, hypot, log  # log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter, defaultdict, deque
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint


def ceil(a, b): return (a + b - 1) // b


inf = float('inf')
mod = 10 ** 9 + 7


def pprint(*A):
    for a in A:     print(*a, sep='\n')


def INT_(n): return int(n) - 1


def MI(): return map(int, input().split())


def MF(): return map(float, input().split())


def MI_(): return map(INT_, input().split())


def LI(): return list(MI())


def LI_(): return [int(x) - 1 for x in input().split()]


def LF(): return list(MF())


def LIN(n: int): return [I() for _ in range(n)]


def LLIN(n: int): return [LI() for _ in range(n)]


def LLIN_(n: int): return [LI_() for _ in range(n)]


def LLI(): return [list(map(int, l.split())) for l in input()]


def I(): return int(input())


def F(): return float(input())


def ST(): return input().replace('\n', '')


def main():
    N = I()
    P = MI()
    emp = [[1] * (N + 1) for _ in range(N + 1)]
    dp = [[inf] * (N + 1) for _ in range(N + 1)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    for x in range(1, N + 1):
        for y in range(1, N + 1):
            ax = min(x - 1, N - x)
            ay = min(y - 1, N - y)
            dp[x][y] = min(ax, ay)
    ans = 0
    for i in P:
        y = (i % N)
        x = (i // N) + 1
        if y == 0:
            y += N
            x -= 1
        ans += dp[x][y]
        emp[x][y] = 0
        q = {(x, y, -1)}
        while q:
            now = q.pop()
            for j in range(len(dx)):
                if j == now[2]:
                    continue
                nx = now[0] + dx[j]
                ny = now[1] + dy[j]
                if 1 <= nx <= N and 1 <= ny <= N and dp[nx][ny] == dp[now[0]][now[1]] + 1 + emp[now[0]][now[1]]:
                    dp[nx][ny] -= 1
                    q.add((nx, ny, (j + 2) % 4))
    print(ans)


if __name__ == '__main__':
    main()

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.popleft()
            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
    def bfs(sy, sx):
        que = deque([(sy, sx)])
        popleft = que.popleft; append = que.append
        while que:
            y, x = popleft()
            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
import queue
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 = queue.Queue()
	q.put(1000*x+y)
	cl = set()
	cl.add(x*1000+y)
	while not q.empty():
		v = q.get()
		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.put((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:
#!/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 == -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:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import collections
import itertools


class Cell(object):

  def __init__(self):
    self.value = None
    self.exist = 1
    self.neighbors = []


def main():
  N = int(input())
  cells = [[Cell() for _ in range(N)] for _ 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.append(cells[y][x - 1])

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

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

    if y == N - 1:
      c.value = 0
    else:
      c.neighbors.append(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

    cells[y][x].value -= 1
    cells[y][x].exist = 0

    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:
from collections import deque
n = int(input())
p = list(map(int,input().split()))
maze = [[0]*(n+2)] + [[0]+[-1]*n+[0] for i in range(n)] + [[0]*(n+2)]
opt = [(1,0),(0,1),(-1,0),(0,-1)]
ans = 0
for k in p:
    # print(k,ans)
    lim = 250
    j = (k-1) // n +1
    i = (k-1) % n +1
    temp = [[-1]*(n+2) for i in range(n+2)]
    temp[j][i] = 0
    dq = deque([(j,i)])
    while dq:
            x,y = dq.popleft()
            for l in opt:
                x1,y1 = x+l[0],y+l[1]
                if maze[x1][y1] == -1 and temp[x1][y1] == -1:
                    temp[x1][y1] = temp[x][y] + 1
                    dq.append((x1,y1))
                if maze[x1][y1] == 1 and temp[x1][y1] == -1:
                    temp[x1][y1] = temp[x][y]
                    dq.appendleft((x1,y1))
                if maze[x1][y1] == 0:
                    ans += temp[x][y]
                    dq = False
                    maze[j][i] = 1
                    # print(x,y)
                    break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
  global hl,n,st
  n = int(input())
  p = [int(i)-1 for i in input().split()]
  st = [[1]*n for _ in range(n)]
  ans = 0
  for i in p:
    ph,pw = (i//n,i%n)
    st[ph][pw] = 0
    if ph != 0 and pw != 0 and ph != n-1 and pw != n-1:
      hl = [[n]*n for _ in range(n)]
      hl[ph][pw] = 0
      f(ph,pw)
      hlmin = min(min(hl[0]),min(hl[-1]),min([min(j[0],j[-1]) for j in hl[1:-1]]))
      ans += hlmin
  print(ans)

def f(h,w):
  global hl,n,st
  if h == 0 or w == 0 or h == n-1 or w == n-1:
    return
  now = hl[h][w]
  for i in ((1,0),(-1,0),(0,1),(0,-1)):
    if hl[h+i[0]][w+i[1]] > now + st[h+i[0]][w+i[1]]:
      hl[h+i[0]][w+i[1]] = now + st[h+i[0]][w+i[1]]
      f(h+i[0],w+i[1])

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7)
def cur(i,j):
    rank=g[i][j]+sit[i][j]
    if i+1<n and g[i+1][j]>rank:
        g[i+1][j]=rank
        cur(i+1,j)
    if i-1>-1 and g[i-1][j]>rank:
        g[i-1][j]=rank
        cur(i-1,j)
    if j+1<n and g[i][j+1]>rank:
        g[i][j+1]=rank
        cur(i,j+1)
    if j-1>-1 and g[i][j-1]>rank:
        g[i][j-1]=rank
        cur(i,j-1)

n=int(input())
g=[[min(i,n-1-i,j,n-1-j) for j in range(n)] for i in range(n)]
sit=[[1 for j in range(n)] for i in range(n)]
p=list(map(int,input().split()))

ans=0
for tp in p:
    pi,pj=(tp-1)//n,(tp-1)%n
    sit[pi][pj]=0
    ans+=g[pi][pj]
    cur(pi,pj)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
 
n = int(input())
od = [int(num)-1 for num in input().split()]

current = np.array([[ 1 for i in range(n)] for j in range(n)]) 
mkip = np.array([[ min([i, j, n-1-i, n-1-j]) for i in range(n)] for j in range(n)])

def valid(x, y):
  return 0 <= x and x < n and 0 <= y and y < n

def update(current, mkip, x, y):
  current[x][y] = 0
  q = deque([])
  q.append((x, y))
  while len(q) > 0:
    x, y = q.popleft()
    t1 = mkip[x][y] + current[x][y]
    if valid(x+1, y) and mkip[x+1][y] > t1:
        mkip[x+1][y] = t1
        q.append((x+1, y))
        
    if valid(x, y+1) and mkip[x][y+1] > t1:
        mkip[x][y+1] = t1
        q.append((x, y+1))
        
    if valid(x-1, y) and mkip[x-1][y] > t1:
        mkip[x-1][y] = t1
        q.append((x-1, y))

    if valid(x, y-1) and mkip[x][y-1] > t1:
        mkip[x][y-1] = t1
        q.append((x, y-1))
        
  #return current, mkip
        
count = 0
for i in range(len(od)):
  x, y = int(od[i] / n), od[i] % n
  count += mkip[x][y]
  #current, mkip = 
  update(current, mkip, x, y)
  
  
print(count)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = list(map(int, input().split()))
for i in range(len(P)):
    P[i] -= 1

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

presence = [[1 for j in range(N)] for i in range(N)]

ans = 0
for i in range(len(P)):
    x = P[i] // N
    y = P[i] % N
    ans += dp[x][y] - 1
    presence[x][y] = 0

    Q = [(x, y)]
    while Q:
        x, y = Q.pop()
        new_value = presence[x][y] + min(
            dp[x - 1][y], dp[x + 1][y], dp[x][y - 1], dp[x][y + 1]
        )
        if new_value != dp[x][y]:
            dp[x][y] = new_value
            if 1 <= x and dp[x - 1][y] > presence[x - 1][y] + dp[x][y]:
                Q.append((x - 1, y))
            if x < N - 1 and dp[x + 1][y] > presence[x + 1][y] + dp[x][y]:
                Q.append((x + 1, y))
            if 1 <= y and dp[x][y - 1] > presence[x][y - 1] + dp[x][y]:
                Q.append((x, y - 1))
            if y < N - 1 and dp[x][y + 1] > presence[x][y + 1] + dp[x][y]:
                Q.append((x, y + 1))

print(ans)
pass

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

    xy_lst = []
    for q in p:
        x, y = divmod(q-1, n)
        xy_lst.append([x+1, y+1])

    seat = [[-1 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 = [[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):
            yet[i][j] = 1

    cnt = 0
    direct = [[-1,0], [1,0], [0,-1], [0,1]]
    for xy in xy_lst:
        x, y = xy
        cnt += seat[x][y]
        seat[x][y] -= 1
        yet[x][y] = 0
        que = deque([xy])

        while que:
            x0, y0 = que.popleft()
            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:
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 = [[0]*(N+2) for _ in range(N+2)]
    queue = [(0, s)]
    heapq.heapify(queue)
    while queue:
        c, (y, x) = heapq.heappop(queue)
        if checked[y][x]:
            continue
        checked[y][x] = 1
        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 not checked[ny][nx]:
                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 sys
import queue

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

#+++++

def gg(nn, x, y, n, is_sit):
	q = queue.Queue()
	q.put(1000*x+y)
	cl = set()
	cl.add(x*1000+y)
	while not q.empty():
		v = q.get()
		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.put((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:
# 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
    def bfs(sy, sx):
        que = deque([(sy, sx)])
        popleft = que.popleft; append = que.append
        while que:
            y, x = popleft()
            cur = dp[y][x]
            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:
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)]
Removed = [[0]*N for x in range(N)]
# for m in Mat:
#     print(m)
# print()
Dy, Dx = [1,0,-1,0], [0,1,0,-1]
ans = 0
closed = [[False]*N for _ in range(N)]
for p in P:
    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))
                    closed[uy][ux] = True
                    clsd.append((uy, ux))
            else:
                if Mat[uy][ux] >= val+2:
                    Mat[uy][ux] = val+1
                    st.append((uy, ux))
                    closed[uy][ux] = True
                    clsd.append((uy, ux))
    for y, x in clsd:
        closed[y][x] = False
# for m in Mat:
#     print(m)
print(ans)