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(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)])
        while q:
            now = q.popleft()
            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.append((nx, ny))
    print(ans)


if __name__ == '__main__':
    main()

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)]
    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
            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 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:
from math import inf
from collections import defaultdict


def update(current, weight, visited):
    tmp_w = weight[current]
    x, y = current
    next_coords = (
        (x, y + 1),
        (x + 1, y),
        (x - 1, y),
        (x, y - 1)
    )
    for coord in next_coords:
        if (
            coord in visited
            or not (-1 < coord[0] < N)
            or not (-1 < coord[1] < N)
            ):
            continue
        elif weight[coord] > tmp_w:
            weight[coord] = tmp_w + table[coord[0]][coord[1]]


def process(p):
    p -= 1
    x, y = (p // N, p % N)
    table[x][y] = 0
    for coord in (
            (x, y + 1),
            (x + 1, y),
            (x - 1, y),
            (x, y - 1)
        ):
        if result_dict.get(coord) == 0:
            result_dict[coord] = 0
            return 0
    weight = defaultdict(lambda: inf)
    visited = set()
    weight[(x, y)] = 0
    while x not in [0, N-1] and y not in [0, N-1]:
        update((x, y), weight, visited)
        visited.add((x, y))
        weight.pop((x, y))
        x, y = min(weight.keys(), key=lambda x: weight.get(x))
    result_dict[(x, y)] = weight[(x, y)]
    return weight[(x, y)]

result_dict = {}
N = int(input())
P = (int(s) for s in input().split())
table = [[1] * N for _ in range(N)]
print(sum(process(i) for i in P))

Submission status: Time Limit Exceeded

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

d = [[-1 for _ in range(n)] for _ in range(n)]
used = [[False for _ in range(n)] for _ in range(n)]
for i in range(n):
	for j in range(n):
		d[i][j] = min(i, j, n-1-i, n-1-j)
#for e in d:
#	print(*e)

DI = [1, 0, -1, 0]
DJ = [0, 1, 0, -1]

ans = 0
for x in p:
	x -= 1
	i, j = x//n, x%n
	ans += d[i][j]
	used[i][j] = True
	q = deque()
	for di, dj in zip(DI, DJ):
		if not ((0 <= i+di < n) and (0 <= j+dj < n)):
			continue
		if d[i+di][j+dj] > d[i][j]:
			d[i+di][j+dj] = d[i][j]
			q.append((i+di)*n + j+dj)
	while q:
		l = q.popleft()
		i, j = l//n, l%n
		for di, dj in zip(DI, DJ):
			if not ((0 <= i+di < n) and (0 <= j+dj < n)):
				continue
			if used[i][j]:
				if d[i+di][j+dj] > d[i][j]:
					d[i+di][j+dj] = d[i][j]
					q.appendleft((i+di)*n + j+dj)
			else:
				if d[i+di][j+dj] > d[i][j] + 1:
					d[i+di][j+dj] = d[i][j] + 1
					q.append((i+di)*n + j+dj)
	#print("----")
	#for e in d:
		#print(*e)

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

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):
    if i < n or n**2-n <= i or i%n==0 or i%n==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 s == 10:
#             print(_ci, _i)
        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:
#                         print(s,_min)
                        return 0
                heapq.heappush(hq, [_list[_j],_j])
#     print(s,_min)
    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
#     print(_tmp)
    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:
N = int(input())
Ps = list(map(lambda x: int(x), input().split()))

inf = 10**18
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] for i in range(N+2)]
cost[0] = [0]*(N+2)
cost[-1] = [0]*(N+2)
ans = 0
for i in range(N**2):
    p = Ps[i]-1
    y = p//N+1
    x = p%N+1
    ans += djikstra((y, x))
    cost[y][x] = 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import queue
input = sys.stdin.readline
n = int(input())
p = list(map(int,input().split()))
m = [min([n-1-i,i,j,n-1-j]) for j in range(n) for i in range(n)]
b = [True for _ in range(n**2)]
c = 0
for pi in p:
  b[pi-1] = False
  c += m[pi-1]
  q = queue.Queue()
  q.put(pi-1)
  while not q.empty():
    ni = q.get()
    for ai in [-1,+1,-n,+n]:
      if 0<=ni+ai and ni+ai<=n**2-1:
        if b[ni] == True:
          if m[ni+ai] > m[ni]+1:
            m[ni+ai] = m[ni] + 1
            q.put(ni+ai)
        else:
          if m[ni+ai] > m[ni]:
            m[ni+ai] = m[ni]
            q.put(ni+ai)    
print(c)

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
    Q = deque()
    now = (0, sx, sy)
    Q.append(now)
    D = [[False] * N for _ in range(N)]
    Done = [[False] * N for _ in range(N)]
    D[sy][sx] = True
    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:
                Done[sy][sx] = True
            break
        if Done[y][x]:
            ans += fatigue
            if fatigue == 0:
                Done[sy][sx] = True
            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]:
                continue
            else:
                D[ny][nx] = True
                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:

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)
            

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
    propagete(r)
    
print(res)

#print(dp)

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
    Q = deque()
    now = (0, sx, sy)
    Q.append(now)
    D = [[False] * N for _ in range(N)]
    Done = [[False] * N for _ in range(N)]
    D[sy][sx] = True
    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:
                Done[sy][sx] = True
            break
        if Done[y][x]:
            ans += fatigue
            if fatigue == 0:
                Done[sy][sx] = True
            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]:
                continue
            else:
                D[ny][nx] = True
                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:
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 point in graph[node].keys():
            w=graph[node][point]
            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={i:defaultdict(lambda x:1) 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][node+num]=1
                    graph[node+num][node]=1
    ans=0
    for i in range(N):
        graph[0][i+1]=0
        graph[i+1][0]=0
        graph[0][N*(N-1)+i+1]=0
        graph[N*(N-1)+i+1][0]=0##
    #####ここから上は全部初期のグラフの設定####
        
    vanished=[False for i in range(N**2+1)]
    for i in range(N):
        graph[0][i*N+1]=0
        graph[i*N+1][0]=0
        graph[0][i*N+N]=0
        graph[i*N+N][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][num+some]=0
                    graph[num+some][some]=0
                else:
                    graph[num+some][some]=0
    print(ans)    
if __name__=="__main__":
    main()

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:            
      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]
        if G[ny][nx] == 0:
          V[ny][nx] = True
        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
  c = escape(F,y,x,n)  
  ans += c
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N = int(input())
p = list(map(int, input().split()))
thea = [[1]*N for i in range(N)]
NN = N**2
ans = 0
nb = [(-1, 0), (0, -1), (1, 0), (0, 1)]

def bfs(sx, sy):
    destroy = [[-1] * N for _ in range(N)]
    q = deque([(sx, sy)])
    destroy[sx][sy] = 0
    while q:
        x, y = q.popleft()
        for dx, dy in nb:
            nx = x + dx
            ny = y + dy
            if 0 <= nx and nx < N and 0 <= ny and ny < N:
                if destroy[nx][ny] == -1:
                    if thea[nx][ny] == 1:
                        destroy[nx][ny] = destroy[x][y] + 1
                        q.append((nx, ny))
                    else:
                        destroy[nx][ny] = destroy[x][y]
                        q.appendleft((nx, ny))
            else:
                return destroy[x][y]

for i in p:
    i -= 1
    sho = i//N
    ama = i%N
    if sho == 0 or sho == N-1 or ama == 0 or ama == N-1:
        thea[sho][ama] = 0
    else:
        ans += bfs(sho, ama)
        thea[sho][ama] = 0

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from math import inf
from collections import defaultdict


def update(current, weight, visited):
    tmp_w = weight[current]
    x, y = current
    next_coords = (
        (x, y + 1),
        (x + 1, y),
        (x - 1, y),
        (x, y - 1)
    )
    for coord in next_coords:
        if (
            coord in visited
            or not (-1 < coord[0] < N)
            or not (-1 < coord[1] < N)
            ):
            continue
        elif weight[coord] > tmp_w:
            weight[coord] = tmp_w + table[coord[0]][coord[1]]


def process(p):
    p -= 1
    x, y = (p // N, p % N)
    weight = defaultdict(lambda: inf)
    visited = set()
    weight[(x, y)] = 0
    table[x][y] = 0
    while x not in [0, N-1] and y not in [0, N-1]:
        update((x, y), weight, visited)
        visited.add((x, y))
        weight.pop((x, y))
        x, y = min(weight.keys(), key=lambda x: weight.get(x))
    return weight[(x, y)]

N = int(input())
P = (int(s) for s in input().split())
table = [[1] * N for _ in range(N)]
print(sum(process(i) for i in P))

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:            
      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]
        if G[ny][nx] == 0:
          V[ny][nx] = False
        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
  c = escape(F,y,x,n)  
  ans += c
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
import sys


input = sys.stdin.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
    Q = []
    now = (0, sx, sy)
    heapq.heappush(Q, now)
    D = [[False] * N for _ in range(N)]
    Done = [[False] * N for _ in range(N)]
    D[sy][sx] = True
    while len(Q) > 0:
        fatigue, x, y = heapq.heappop(Q)
        if x < 0 or y < 0 or x >= N or y >= N:
            ans += fatigue
            if fatigue == 0:
                Done[sy][sx] = True
            break
        if Done[y][x]:
            ans += fatigue
            if fatigue == 0:
                Done[sy][sx] = True
            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:
                heapq.heappush(Q, (fatigue, nx, ny))
            elif D[ny][nx]:
                continue
            else:
                D[ny][nx] = True
                if Maze[ny][nx] != 0:
                    heapq.heappush(Q, (fatigue + 1, nx, ny))
                else:
                    heapq.heappush(Q, (fatigue, nx, ny))

    Maze[sy][sx] = 0

print(ans)

Submission status: Time Limit Exceeded

Solution code:

"""

外周への最小距離を求める
O(1)かlogぐらいで1人求められる必要がある

逆に座っていく？
座ったことにより、距離を伸ばしてしまったら+1
外周との最短距離とは何か？

普通はbfsで求められる
あるやつからあるやつへの最短経路を維持して置いて操作する？
最短の方向に矢印
抜けるたび最短を更新？

"""
from collections import deque
N = int(input())
lis = [[0]*N for i in range(N)]
exsist = [ [1] * N for i in range(N) ] 

for i in range(N):
    for j in range(N):

        lis[i][j] = min(i,j,N-1-i,N-1-j)

P = list(map(int,input().split()))
ans = 0
q = deque([])

for loop in range(N**2):

    ni = (P[loop]-1)//N
    nj = (P[loop]-1)% N

    ans += lis[ni][nj]
    exsist[ni][nj] = 0

    q.append((ni,nj))

    while len(q) > 0:

        now = q.popleft()
        i,j = now

        if i != 0 and lis[i-1][j] > lis[i][j] + exsist[i][j]:
            lis[i-1][j] = lis[i][j] + exsist[i][j]
            q.append((i-1,j))
        if i != N-1 and lis[i+1][j] > lis[i][j] + exsist[i][j]:
            lis[i+1][j] = lis[i][j] + exsist[i][j]
            q.append((i+1,j))
        if j != 0 and lis[i][j-1] > lis[i][j] + exsist[i][j]:
            lis[i][j-1] = lis[i][j] + exsist[i][j]
            q.append((i,j-1))
        if j != N-1 and lis[i][j+1] > lis[i][j] + exsist[i][j]:
            lis[i][j+1] = lis[i][j] + exsist[i][j]
            q.append((i,j+1))

print (ans)

Submission status: Time Limit Exceeded

Solution code:
def kousin(klist, 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(klist, 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)
        #print("!")
        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(klist, [ [now1, now2, klist[now1][now2]] ])

print(answer)

Submission status: Time Limit Exceeded

Solution code:
import sys
import queue
input = sys.stdin.readline
n = int(input())
p = list(map(int,input().split()))
m = [[min([n-1-i,i,j,n-1-j]) for j in range(n)]for i in range(n)]
b = [[True for _ in range(n)] for _ in range(n)]
c = 0
for pi in p:
  j = (pi-1)%n
  i = (pi-1)//n
  b[i][j] = False
  c += m[i][j]
  q = queue.Queue()
  q.put((i,j))
  while not q.empty():
    ni,nj = q.get()
    for ai,aj in [(0,1),(1,0),(-1,0),(0,-1)]:
      if all([0<=ni+ai,ni+ai<=n-1,0<=nj+aj,nj+aj<=n-1]):
        if b[ni][nj] == True:
          if m[ni+ai][nj+aj] > m[ni][nj]+1:
            m[ni+ai][nj+aj] = m[ni][nj] + 1
            q.put((ni+ai,nj+aj))
        else:
          if m[ni+ai][nj+aj] > m[ni][nj]:
            m[ni+ai][nj+aj] = m[ni][nj]
            q.put((ni+ai,nj+aj))       
print(c)