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
input=sys.stdin.readline
import heapq
def dijkstra(s,graph,n):
    dist=[float("inf") for i in range(n+1)]
    dist[s]=0
    pq=[]
    heapq.heapify(pq)
    heapq.heappush(pq,(0,s))
    while pq:
        mini_dis,node=heapq.heappop(pq)
        if dist[node]<mini_dis: continue
        for w,point in graph[node]:
            if dist[point]<w:continue
            newlen=dist[node]+w
            if newlen<dist[point]:
                heapq.heappush(pq,(newlen,point))
                dist[point]=newlen
    return dist
def main():
    N=int(input())
    que=list(map(int,input().split()))
    from collections import defaultdict
    dif=[1,-1,N,-N]
    graph=[[] for i in range(N**2+1)]
    for i in range(N):
        for j in range(N):
            node=N*i+j+1
            for num in dif:
                if 1<=node+num<=N**2:
                    graph[node].append((1,node+num))
                    graph[node+num].append((1,node))
    ans=0
    for i in range(N):
        graph[0].append((0,i+1))
        graph[i+1].append((0,0))
        graph[0].append((0,N*(N-1)+i+1))
        graph[N*(N-1)+i+1].append((0,0))
        
    vanished=[False for i in range(N**2+1)]
    
    for i in range(N):
        graph[0].append((0,i*N+1))
        graph[i*N+1].append((0,0))
        graph[0].append((0,i*N+N))
        graph[i*N+N].append((0,0))
    for some in que:
        ans+=dijkstra(some,graph,N**2)[0]
        vanished[some]=True
        for num in dif:
            if 1<=num+some<=N**2:
                if vanished[num+some]:
                    graph[some].append((0,num+some))
                    graph[num+some].append((0,some))
                else:
                    graph[num+some].append((0,some))
    print(ans)    
if __name__=="__main__":
    main()

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((x,y))
	cl = set()
	cl.add(x*1000+y)
	while not q.empty():
		x,y = q.get()
		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, 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())
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:
                Q.append((x - 1, y))
            if x < N - 1:
                Q.append((x + 1, y))
            if 1 <= y:
                Q.append((x, y - 1))
            if y < N - 1:
                Q.append((x, y + 1))

print(ans)
pass

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 = deque([(x, y, -1)])
        while q:
            now = q.popleft()
            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.append((nx, ny, (j + 2) % 4))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import pprint
from collections import defaultdict
N = int(input())
edges = defaultdict(set)
for i in range(1, N * N + 1):
    e = []
    if i <= N:
        e.append(0)
    else:
        e.append(i - N)

    if i % N == 0:
        e.append(0)
    else:
        e.append(i + 1)

    if i % N == 1:
        e.append(0)
    else:
        e.append(i - 1)

    if i > N * (N - 1):
        e.append(0)
    else:
        e.append(i + N)
    e = set(e)
    for v in e:
        edges[v].add(i)
        edges[i].add(v)

# print(edges)
vcost = {0: -1}
front = [0]
cost = 0
while front:
    newFront = []
    for p in front:
        for n in edges[p]:
            if n not in vcost:
                vcost[n] = cost
                newFront.append(n)
    front = newFront
    cost += 1

# print(vcost)


def update(xs, newcost):
    for x in xs:
        if vcost[x] > newcost:
            vcost[x] = newcost
            update(edges[x], newcost + 1)


PS = [int(x) for x in input().split()]
cost = 0
for p in PS:
    cost += vcost[p]
    newcost = min(vcost[i] for i in edges[p]) + 1
    update(edges[p], newcost)
    for n in edges[p]:
        edges[n].update(edges[p])

print(cost)

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()
    if valid(x+1, y) and mkip[x+1][y] > mkip[x][y] + current[x][y]:
        mkip[x+1][y] = mkip[x][y] + current[x][y]
        q.append((x+1, y))
        
    if valid(x, y+1) and mkip[x][y+1] > mkip[x][y] + current[x][y]:
        mkip[x][y+1] = mkip[x][y] + current[x][y]
        q.append((x, y+1))
        
    if valid(x-1, y) and mkip[x-1][y] > mkip[x][y] + current[x][y]:
        mkip[x-1][y] = mkip[x][y] + current[x][y]
        q.append((x-1, y))

    if valid(x, y-1) and mkip[x][y-1] > mkip[x][y] + current[x][y]:
        mkip[x][y-1] = mkip[x][y] + current[x][y]
        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())
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]:
                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 = near[ny][nx]
            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:
from collections import deque
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n = inn()
a = inl()
s = [[0]*n for i in range(n)]
emp = [[False]*n for i in range(n)]
for i in range(n):
    for j in range(n):
        s[i][j] = min([i,n-1-i,j,n-1-j])
sm = 0
for z in a:
    x = (z-1)//n
    y = (z-1)%n
    sm += s[x][y]
    emp[x][y] = True
    q = deque([(x,y)])
    while len(q)>0:
        i,j = q.popleft()
        p = s[i][j]+(0 if emp[i][j] else 1)
        for dx,dy in [(0,1),(0,-1),(1,0),(-1,0)]:
            u = i+dx
            v = j+dy
            if 0<=u<n and 0<=v<n and s[u][v]>p:
                s[u][v] = p
                q.append((u,v))
print(sm)

Submission status: Time Limit Exceeded

Solution code:
def kousin(koho):
    koho2=[]
    for kh in koho:
        tate=kh[0]
        yoko=kh[1]
        tesu=kh[2]
        if clist[tate][yoko]==1:
            tesu+=1
        
        if tate==0:
            koho2.append([tate+1, yoko, tesu])
            if yoko==0:
                koho2.append([tate, yoko+1, tesu])
            elif yoko==n-1:
                koho2.append([tate, yoko-1, tesu])
            else:
                koho2.append([tate, yoko+1, tesu])
                koho2.append([tate, yoko-1, tesu])
        elif tate==n-1:
            koho2.append([tate-1, yoko, tesu])
            if yoko==0:
                koho2.append([tate, yoko+1, tesu])
            elif yoko==n-1:
                koho2.append([tate, yoko-1, tesu])
            else:
                koho2.append([tate, yoko+1, tesu])
                koho2.append([tate, yoko-1, tesu])
        else:
            koho2.append([tate-1, yoko, tesu])
            koho2.append([tate+1, yoko, tesu])
            if yoko==0:
                koho2.append([tate, yoko+1, tesu])
            elif yoko==n-1:
                koho2.append([tate, yoko-1, tesu])
            else:
                koho2.append([tate, yoko+1, tesu])
                koho2.append([tate, yoko-1, tesu])
    koho3=[]
    for kh2 in koho2:
        tate=kh2[0]
        yoko=kh2[1]
        tesu=kh2[2]
        if klist[tate][yoko]==tesu+1:
            klist[tate][yoko]=tesu
            koho3.append([tate, yoko, tesu])
        
    koho=koho3
    
    if koho!=[]:
        kousin(koho)
    

n=int(input())
klist=[]
clist=[]

for i in range(n):
    now=[]
    if i<(n+1)//2:
        for j in range(i):
            now.append(j)
        now+=[i]*(n-i*2)
        for j in range(i):
            now.append(i-j-1)
    else:
        for j in range(n-i):
            now.append(j)
        now+=[n-i-1]*(i*2-n)
        for j in range(n-i):
            now.append(n-i-j-1)
    klist.append(now)
    clist.append([1]*n)

answer=0

plist = list(map(int, input().split()))
for pl in plist:
    now1=(pl-1)//n
    now2=(pl-1)%n
    answer+=klist[now1][now2]
    clist[now1][now2]=0
    kousin([ [now1, now2, klist[now1][now2]] ])

#print(klist)
print(answer)

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]:
                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 = [[inf]*(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 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([[ -1 for i in range(n)] for j in range(n)])

for i in range(n):
  for j in range(n):
    cand = [i, j, n-1-i, n-1-j]
    minval = min(cand)
    mkip[i][j] = minval

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()
    if valid(x+1, y) and mkip[x+1][y] > mkip[x][y] + current[x][y]:
        mkip[x+1][y] = mkip[x][y] + current[x][y]
        q.append((x+1, y))
        
    if valid(x, y+1) and mkip[x][y+1] > mkip[x][y] + current[x][y]:
        mkip[x][y+1] = mkip[x][y] + current[x][y]
        q.append((x, y+1))
        
    if valid(x-1, y) and mkip[x-1][y] > mkip[x][y] + current[x][y]:
        mkip[x-1][y] = mkip[x][y] + current[x][y]
        q.append((x-1, y))

    if valid(x, y-1) and mkip[x][y-1] > mkip[x][y] + current[x][y]:
        mkip[x][y-1] = mkip[x][y] + current[x][y]
        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:
import sys
input = sys.stdin.readline
 
n = int(input())
P = list(map(int,input().split()))
for i in range(n**2):
    P[i] -= 1
 
 
M = [[] for i in range(n**2)]
DD = [[-1,0],[1,0],[0,1],[0,-1]]
V = [1] * (n**2)
for i in range(n**2):
    x = i//n
    y = i%n
    for d in range(4):
        gx = x + DD[d][0]
        gy = y + DD[d][1]
        if 0 <= gx < n and 0 <= gy < n:
            g = gx*n + gy
            M[i].append(g)
 
D = [0] * (n**2)
for i in range(n**2):
    x = i//n
    y = i%n
    D[i] = min(x, n-1-x, y, n-1-y)
 
ans = 0
for i in range(n**2):
    # print(D)
    ans += D[P[i]]
    V[P[i]] = 0
    
    s = 0
    Q = [P[i]]
    while s < len(Q):
        mi = D[Q[s]]
        for j in M[Q[s]]:
            if D[j] > D[Q[s]] + V[Q[s]]:
                Q.append(j)
                D[j] = D[Q[s]] + V[Q[s]]
        s += 1
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([[ -1 for i in range(n)] for j in range(n)])
mvec = np.array([[ -1 for i in range(n)] for j in range(n)])

for i in range(n):
  for j in range(n):
    cand = [i, j, n-1-i, n-1-j]
    minval = min(cand)
    mkip[i][j] = minval
    mvec[i][j] = int(minval == i)*8+int(minval == j)*4+int(minval == n-1-i)*2+int(minval == n-1-j)*1

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

def update(current, mkip, mvec, x, y):
  current[x][y] = 0
  q = deque([])
  q.append((x, y))
  while len(q) > 0:
    x, y = q.popleft()
    if valid(x+1, y):
      if mkip[x+1][y] > mkip[x][y] + current[x][y]:
        mkip[x+1][y] = mkip[x][y] + current[x][y]
        mvec[x+1][y] = 8
        q.append((x+1, y))
      elif mkip[x+1][y] == mkip[x][y] + current[x][y]:
        mvec[x+1][y] = mvec[x+1][y]|8
        
    if valid(x, y+1):
      if mkip[x][y+1] > mkip[x][y] + current[x][y]:
        mkip[x][y+1] = mkip[x][y] + current[x][y]
        mvec[x][y+1] = 4
        q.append((x, y+1))
      elif mkip[x][y+1] == mkip[x][y] + current[x][y]:
        mvec[x][y+1] = mvec[x][y+1]|4
        
    if valid(x-1, y):      
      if mkip[x-1][y] > mkip[x][y] + current[x][y]:
        mkip[x-1][y] = mkip[x][y] + current[x][y]
        mvec[x-1][y] = 2
        q.append((x-1, y))
      elif mkip[x-1][y] == mkip[x][y] + current[x][y]:
        mvec[x-1][y] = mvec[x-1][y]|2

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

Submission status: Time Limit Exceeded

Solution code:
import heapq
push = heapq.heappush
pop = heapq.heappop

def main():

    N = int(input())
    S = list(map(int, input().split()))
    NN = N**2
    P = [True]*(NN)

    def bfs(loc):
        data = [True]*(NN)
        data[loc] = 1
        s = P[loc]
        stack = [(0, loc)]
        while True:
            d, v = pop(stack)
            # 上
            if v-N >= 0:
                if data[v-N]:
                    data[v-N] = False
                    if P[v-N]:
                        push(stack, (d+1, v-N))
                    else:
                        push(stack, (d, v-N))
            else:
                return d
            # 左
            if v%N != 0:
                if data[v-1]:
                    data[v-1] = False
                    if P[v-1]:
                        push(stack, (d+1, v-1))
                    else:
                        push(stack, (d, v-1))
            else:
                return d
            # 右
            if (v+1)%N != 0 and v != NN-1:
                if data[v+1]:
                    data[v+1] = False
                    if P[v+1]:
                        push(stack, (d+1, v+1))
                    else:
                        push(stack, (d, v+1))
            else:
                return d
            # 下
            if v+N < NN:
                if data[v+N]:
                    data[v+N] = False
                    if P[v+N]:
                        push(stack, (d+1, v+N))
                    else:
                        push(stack, (d, v+N))
            else:
                return d

    ans = 0
    for i in range(NN):
        P[S[i]-1] = False
        ans += bfs(S[i]-1)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

input = sys.stdin.buffer.readline

N = int(input())
Order = list(map(int, input().split()))
Maze = [[1] * N for _ in range(N)]
dy = (1, 0, -1, 0)
dx = (0, 1, 0, -1)
ans = 0
for o in Order:
    o -= 1
    sx = o % N
    sy = o // N
    D = [[0] * N for _ in range(N)]
    if sy == 0 or sx == 0 or sy == N-1 or sx == N-1:
        D[sy][sx] = 2
    else:
        Q = deque()
        now = (0, sx, sy)
        Q.append(now)
        D[sy][sx] = 1
        while len(Q) > 0:
            fatigue, x, y = Q.popleft()
            if x < 0 or y < 0 or x >= N or y >= N:
                ans += fatigue
                if fatigue == 0:
                    D[sy][sx] = 2
                break
            if D[y][x] == 2:
                ans += fatigue
                if fatigue == 0:
                    D[sy][sx] = 2
                break
            for d in range(4):
                ny = y + dy[d]
                nx = x + dx[d]
                if nx < 0 or ny < 0 or nx >= N or ny >= N:
                    Q.appendleft((fatigue, nx, ny))
                elif D[ny][nx] == 1:
                    continue
                else:
                    D[ny][nx] = 1
                    if Maze[ny][nx] != 0:
                        Q.append((fatigue + 1, nx, ny))
                    else:
                        Q.appendleft((fatigue, nx, ny))

    Maze[sy][sx] = 0

print(ans)

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
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)]
    closed = {(y,x)}
    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 (uy, ux) in closed:
                continue
            ur = Removed[uy][ux]
            if vr:
                if Mat[uy][ux] >= val+1:
                    Mat[uy][ux] = val
                    st.append((uy, ux))
                    closed.add((uy, ux))
            else:
                if Mat[uy][ux] >= val+2:
                    Mat[uy][ux] = val+1
                    st.append((uy, ux))
                    closed.add((uy, ux))
# for m in Mat:
#     print(m)
print(ans)



# Parents = [[] for _ in range(N*N)]
# Children = [set() for _ in range(N*N)]
# for yx in range(N*N):
#     y, x = divmod(yx, N)
#     v = Mat[y][x]
#     for dy, dx in zip(Dy, Dx):
#         uy = y + dy
#         ux = x + dx
#         uyx = uy*N + ux
#         if not (0<=uy<N and 0<=ux<N):
#             continue
#         u = Mat[uy][ux]
#         if u < v:
#             Parents[uyx].append(yx)
#             Children[yx].append(uyx)
#         elif u > v:
#             Parents[yx].append(uyx)
#             Children[uyx].append(yx)
# for p in P:
#     y, x = divmod(p, N)
#     ans += Mat[y][x]
#     #print(p, Mat[y][x])
#     Mat[y][x] -= 1
#     st = [(y, x)]
#     for parent in Parents[]:
#         for child in Children:
            
#     while st:
#         vy, vx = st.pop()
#         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 Mat[uy][ux] - 2 == val:
#                 Mat[uy][ux] -= 1
#                 st.append((uy, ux))

Submission status: Time Limit Exceeded

Solution code:
# AGC044 B Joker
from collections import deque
import heapq

n = int(input())
p_dq = deque([int(x) for x in input().split()])

def is_edge(i, n):
    _ = i%n
    if i < n or n**2-n <= i or _==0 or _==n-1:
        return True
    else:
        return False

def dijkstra(s, n, c_list):
    _list = [float("Inf")]*(n**2)
    _list[s] = 0
    _min = n
    hq = [[0,s]]
    heapq.heapify(hq)
    while len(hq) > 0:
        _ci, _i = heapq.heappop(hq)
        if _list[_i] < _ci:
            continue
        for _cj,_j in c_list[_i]:
            if _list[_j] > (_list[_i] + _cj):
                _list[_j] = _list[_i] + _cj
                if is_edge(_j,n):
                    _min = min(_min, _list[_j])
                    if _min == 0:
                        return 0
                heapq.heappush(hq, [_list[_j],_j])
    return _min

c_list = [[] for i in range(n**2)]

for i in range(n**2):
    if not(is_edge(i, n)):
        c_list[i].append([1,i-1])
        c_list[i].append([1,i+1])
        c_list[i].append([1,i-n])
        c_list[i].append([1,i+n])
    
ans = 0

for i in range(n**2):
    _tmp = p_dq.popleft() - 1
    if not(is_edge(_tmp, n)):
        ans += dijkstra(_tmp, n, c_list)
    if not(is_edge(_tmp-1,n)):
        c_list[_tmp-1][1][0] = 0
    if not(is_edge(_tmp+1,n)):
        c_list[_tmp+1][0][0] = 0
    if not(is_edge(_tmp-n,n)):
        c_list[_tmp-n][3][0] = 0
    if not(is_edge(_tmp+n,n)):
        c_list[_tmp+n][2][0] = 0

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

input = sys.stdin.buffer.readline

N = int(input())
Order = list(map(int, input().split()))
Maze = [[1] * N for _ in range(N)]
dy = (1, 0, -1, 0)
dx = (0, 1, 0, -1)
ans = 0
for o in Order:
    o -= 1
    sx = o % N
    sy = o // N
    if sy == 0 or sx == 0 or sy == N or sx == N:
        Maze[sy][sx] = 0
    else:
        Q = deque()
        now = (0, sx, sy)
        Q.append(now)
        D = [[0] * N for _ in range(N)]
        D[sy][sx] = 1
        while len(Q) > 0:
            fatigue, x, y = Q.popleft()
            if x < 0 or y < 0 or x >= N or y >= N:
                ans += fatigue
                if fatigue == 0:
                    D[sy][sx] = 2
                break
            if D[y][x] == 2:
                ans += fatigue
                if fatigue == 0:
                    D[sy][sx] = 2
                break
            for d in range(4):
                ny = y + dy[d]
                nx = x + dx[d]
                if nx < 0 or ny < 0 or nx >= N or ny >= N:
                    Q.appendleft((fatigue, nx, ny))
                elif D[ny][nx] == 1:
                    continue
                else:
                    D[ny][nx] = 1
                    if Maze[ny][nx] != 0:
                        Q.append((fatigue + 1, nx, ny))
                    else:
                        Q.appendleft((fatigue, nx, ny))

        Maze[sy][sx] = 0

print(ans)