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
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def solve(N, P):
    W = N + 2
    dp = np.zeros((W, W), np.int32)
    for _ in range(4):
        dp = dp.T[::-1]
        for n in range(1, (N + 1) // 2 + 1):
            dp[n, n:-n] = n
    filled = np.zeros_like(dp)
    filled[1:-1, 1:-1] = 1
    dp = dp.ravel()
    filled = filled.ravel()
    stack = np.empty_like(dp)
    ans = 0
    for n in P:
        n -= 1
        h, w = divmod(n, N)
        v = (h + 1) * W + (w + 1)
        ans += dp[v] - 1
        filled[v] = 0
        k = min(dp[v - 1], dp[v + 1], dp[v - W], dp[v + W])
        if dp[v] == k:
            return ans
        p = 0
        stack[0] = v
        dp[v] = k
        while p >= 0:
            v = stack[p]
            p -= 1
            for dx in (-1, 1, -W, W):
                w = v + dx
                k = dp[v] + filled[w]
                if dp[w] > k:
                    dp[w] = k
                    p += 1
                    stack[p] = w
    return ans

N = int(readline())
P = np.array(read().split(), np.int32)

print(solve(N, P))

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    from collections import deque
    input = sys.stdin.readline
    n = int(input())
    p = [int(i)-1 for i in input().split()]
    c = [[1]*n for _ in range(n)] 
    d = [[0]*n for _ in range(n)]
    for x in range(n):
        for y in range(n):
            d[y][x] += min(min(x, n-x-1), min(y, n-y-1))
    ans = 0
    for i in p:
        x, y = i%n, i//n
        c[y][x] = 0
        ans += d[y][x]
        que = deque([[x, y]])
        while que:
            x, y = que.popleft()
            for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
                nx, ny = x+dx, y+dy
                if 0 <=nx< n and 0<=ny<n:
                    if d[y][x]+c[y][x]<d[ny][nx]:
                        d[ny][nx] = d[y][x]+c[y][x]
                        que.append([nx, ny])
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N=int(input())
edge={i:[] for i in range(0,N**2+1)}

for i in range(1,N**2+1):
    if i%N!=1:
        edge[i].append(i-1)
    else:
        edge[i].append(0)
        edge[0].append(i)
    if i%N!=0:
        edge[i].append(i+1)
    else:
        edge[i].append(0)
        edge[0].append(i)
    if i>N:
        edge[i].append(i-N)
    else:
        edge[i].append(0)
        edge[0].append(i)
    if N**2-N+1>i:
        edge[i].append(i+N)
    else:
        edge[i].append(0)
        edge[0].append(i)

edge[0]=list(set(edge[0]))
P=list(map(int,input().split()))
dist={}
que=deque([(0,0)])
while que:
    v,d=que.popleft()
    if v not in dist:
        dist[v]=0
        dist[v]=d
    else:
        continue
    for nv in edge[v]:
        if nv not in dist:
            if v==0:
                que.appendleft((nv,d))
            else:
                que.append((nv,d+1))

remove=set([0])
ans=0
for i in range(N**2):
    V=P[i]
    ans+=dist[V]
    que=deque([(V,dist[V])])
    remove.add(V)
    while que:
        v,d=que.popleft()
        dist[v]=0
        dist[v]=d
        for nv in edge[v]:
            if v in remove:
                test=d
                if dist[nv]>test:
                    que.appendleft((nv,test))
            else:
                test=d+1
                if dist[nv]>test:
                    que.append((nv,test))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
plist=list(map(int,input().split()))

mat=[[True]*N for _ in range(N)]
answer=0
for p in plist:
  i=(p-1)//N
  j=(p-1)%N
  #print(i,j)
  
  queue=[(i,j)]
  visited=[[False]*N for _ in range(N)]
  reach=False
  d=0
  while queue:
    new_queue=set()
    
    while queue:
      x,y=queue.pop()
      if x==0 or x==N-1 or y==0 or y==N-1:
        reach=True
        break
        
      visited[x][y]=True
      if not visited[x-1][y]:
        if mat[x-1][y]:
          new_queue.add((x-1,y))
        else:
          queue.append((x-1,y))
      if not visited[x+1][y]:
        if mat[x+1][y]:
          new_queue.add((x+1,y))
        else:
          queue.append((x+1,y))
      if not visited[x][y-1]:
        if mat[x][y-1]:
          new_queue.add((x,y-1))
        else:
          queue.append((x,y-1))
      if not visited[x][y+1]:
        if mat[x][y+1]:
          new_queue.add((x,y+1))
        else:
          queue.append((x,y+1))
          
    if reach:
      break
      
    queue=list(new_queue)
    d+=1
    
  #print(i,j,d)
  answer+=d
  mat[i][j]=False
  
print(answer)

Submission status: Time Limit Exceeded

Solution code:
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])
@numba.njit("void(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((N, N), dtype=np.int8)
    Mat = np.zeros((N, N), dtype=np.int16)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    #print(Mat)
    for i in range(N*N):
        p = P[i]
        y, x = divmod(p, N)
        ans += Mat[y][x]
        #print(p, Mat[y][x])
        Removed[y][x] = 1
        #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)
proc(N, P)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

n, *ppp = map(int, sys.stdin.buffer.read().split())

n2 = n + 2
seats = [-1] * n2
row_base0 = list(range(n))
row_base1 = [-1] + row_base0 + [-1]
row_base0.reverse()
row_base2 = [-1] + row_base0 + [-1]
row_base = [min(a, b) for a, b in zip(row_base1, row_base2)]

for i in range(n):
    ud = min(i, n - 1 - i)
    seats.extend(min(a, ud) for a in row_base)
seats.extend([-1] * n2)

is_seated = [False] * n2
is_seated.extend(([False] + [True] * n + [False]) * n)
is_seated.extend([False] * n2)


def pg(aaa):
    for i in range(0, n2 ** 2, n2):
        print(aaa[i:i + n2])
    print()


ans = 0
MOVE = (-n2, -1, 1, n2)
for p in ppp:
    i, j = divmod(p - 1, n)
    i = (i + 1) * n2 + j + 1
    res = seats[i]
    ans += res
    is_seated[i] = False

    q = deque([(res, i + di) for di in MOVE])
    while q:
        val, j = q.popleft()
        if seats[j] <= val:
            continue
        seats[j] = val
        ist = is_seated[j]
        for dj in MOVE:
            nj = j + dj
            if ist:
                nv = val + 1
                if seats[nj] > nv:
                    q.append((nv, nj))
            else:
                if seats[nj] > val:
                    q.appendleft((val, nj))
    # print(p, i, res)
    # pg(seats)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
mod = 1000000007
m = [(0, 1), (1, 0), (-1, 0), (0, -1)]
inf = float('INF')

#solve
def solve():
    n = II()
    p = LI()
    dp = [[min(i, j, n - i - 1, n - j - 1) for i in range(n)] for j in range(n)]
    c = [[1 for i in range(n)] for j in range(n)]
    q = [0] * (n ** 2)
    ans = 0
    for pi in p:
        y, x = divmod(pi - 1, n)
        ans += dp[y][x]
        c[y][x] = 0
        q[0] = pi
        p = 0
        l = 1
        while p != l:
            y, x = divmod(q[p] - 1, n)
            p += 1
            score = dp[y][x] + c[y][x]
            for my, mx in m:
                my += y
                mx += x
                if 0 < my < n - 1 and 0 < mx < n - 1:
                    if dp[my][mx] > score:
                        dp[my][mx] = score
                        q[l] = my * n + mx + 1
                        l += 1
    print(ans)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
import numba
import numpy as np
N = int(input())
P = np.array([int(c)-1 for c in input().split()])
@numba.njit("void(i8,i8[:])")
def proc(N, P):
    ans = 0
    Removed = np.zeros((N, N), dtype=np.int32)
    Mat = np.zeros((N, N), dtype=np.int32)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    #print(Mat)
    for i in range(N*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)]
        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)
proc(N, P)

Submission status: Time Limit Exceeded

Solution code:
from random import shuffle
import numba
import numpy as np
N = int(input())
#P = list(range(N*N))
#shuffle(P)
P = [int(c)-1 for c in input().split()]
#shuffle(P)
#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)
@numba.njit()
def proc(N, P):
    ans = 0
    Removed = np.zeros((N, N), dtype=np.int32)
    Mat = np.zeros((N, N), dtype=np.int32)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    #print(Mat)
    for i in range(N*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)]
        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)
proc(N, P)

Submission status: Time Limit Exceeded

Solution code:
import os

import itertools
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


# MOD = 998244353


def test():
    ans_hist = [INF] * (N ** 2)

    ans = 0
    dist = [INF] * (N ** 2)
    for i, p in enumerate(P):
        p -= 1
        ph, pw = p // N, p % N
        d = min(ph, pw, N - ph - 1, N - pw - 1)

        j = i - 1
        while j >= 0:
            q = P[j] - 1
            qh, qw = q // N, q % N
            d = min(d, dist[q] + abs(ph - qh) + abs(pw - qw) - 1)
            j -= 1

        dist[p] = d
        ans_hist[p] = d

        j = i - 1
        while j >= 0:
            q = P[j] - 1
            qh, qw = q // N, q % N
            dist[q] = min(dist[q], dist[p] + abs(ph - qh) + abs(pw - qw) - 1)
            j -= 1

        ans += d
        # print(p, dist)
    print(ans)
    # print(dist)
    # print(np.array(ans_hist, dtype=int).reshape(N, N))
    return ans


N = int(sys.stdin.buffer.readline())
P = list(map(int, sys.stdin.buffer.readline().split()))

# 解説
dist = [[INF] * N for _ in range(N)]
for h, w in itertools.product(range(N), range(N)):
    dist[h][w] = min(h, w, N - h - 1, N - w - 1)
present = [True] * (N ** 2)

ans = 0
for p in P:
    p -= 1
    h, w = p // N, p % N
    present[p] = False

    ans += dist[h][w]
    stack = [(h, w, dist[h][w])]
    while stack:
        h, w, d = stack.pop()
        d += present[h * N + w]
        for dh, dw in ((0, 1), (1, 0), (0, -1), (-1, 0)):
            if 0 <= h + dh < N and 0 <= w + dw < N:
                if d < dist[h + dh][w + dw]:
                    dist[h + dh][w + dw] = d
                    stack.append((h + dh, w + dw, d))
print(ans)
# test()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    import time
    input = sys.stdin.readline
    sys.setrecursionlimit(10**6)
    N = int(input())
    P = [int(a) for a in input().strip().split()]
    G = [[min(n, N-n-1,i, N-i-1) for i in range(N)] for n in range(N)]
    Gflag = [[1] * N for _ in range(N)]
    ans = 0

    vecs = [(1, 0), (0, 1), (-1, 0), (0, -1)]

    def prg():
        for n in range(N):
            print(G[n], Gflag[n])

    def update(row, col, cost):
        G[row][col] = cost
        for vr, vc in vecs:
            nrow, ncol = row + vr, col + vc
            if nrow < 0 or nrow >= N or ncol < 0 or ncol >= N:
                continue
            if G[nrow][ncol] > cost + Gflag[row][col]:
                update(nrow, ncol, cost + Gflag[row][col])

        return None        

    # prg()
    for p in P:
        # print('p = {}'.format(p))
        row, col = (p-1) // N, (p-1) % N
        ans += G[row][col]
        Gflag[row][col] = 0
        update(row, col, G[row][col])
        # prg()
        # print('ans = {}'.format(ans))

    print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n = int( input() )
p = [ int( px ) for px in input().split() ]
#print( p )

ans = int( 0 )
ex  = [ 1 ] * ( n*n )

for i in range( n*n ):
#    print( i )
#    dp = np.zeros( ( n, n ) )
#    for j in range( n ):
#        dp[ : ] = n*n
    dp = [ n*n ] * ( n*n )
    dp[ p[ i ] - 1 ] = 0
#    print( dp )

    for l in range( n*n ):
        for j in range( n*n ):
#            print( j % n )
            if j <= n-1:
                dp[ j ] = min( [ dp[ j ], dp[ j+n ] + ex[ j ] ] )
            if j % n == 0:
                dp[ j ] = min( [ dp[ j ], dp[ j+1 ] + ex[ j ] ] )
            if j % n == n-1:
                dp[ j ] = min( [ dp[ j ], dp[ j-1 ] + ex[ j ] ] )
            if j >= n*n-n:
                dp[ j ] = min( [ dp[ j ], dp[ j-n ] + ex[ j ] ] )
            if j >= n and j < n*n-n and j % n != 0 and j % n != n-1:
                dmin = min( [ dp[j-n], dp[j+n], dp[j-1], dp[j+1] ] )
                dp[ j ] = min( [ dp[ j ], dmin + ex[ j ] ] )

#    print( dp )
    hate = n*n
    for j, dpj in enumerate( dp ):
        if j <= n-1 or j >= n*n-n or j % n == 0 or j % n == n-1:
            hate = min( hate, dpj )

#    print( hate )
    ans = ans + hate

#    print( dp )
    ex[ p[ i ] - 1 ] = 0
#    print( ex )


print( ans )

Submission status: Time Limit Exceeded

Solution code:
import collections
n = int(input())
P = list(map(int, input().split()))
S = []
for p in P:
    p = p-1
    a = p % n
    b = p//n
    S.append([b, a])


INF = float('inf')
que = collections.deque([])
block = [[INF]*n for _ in range(n)]
for i in range(n):
    block[0][i] = 0
    block[n-1][i] = 0
    que.append([0, i])
    que.append([n-1, i])

for i in range(1, n-1):
    block[i][0] = 0
    block[i][n-1] = 0
    que.append([i, 0])
    que.append([i, n-1])

while que:
    x, y = que.popleft()
    if x+1 <= n-1 and block[x+1][y] == INF:
        block[x+1][y] = block[x][y]+1
        que.append([x+1, y])
    if x-1 >= 0 and block[x-1][y] == INF:
        block[x-1][y] = block[x][y]+1
        que.append([x-1, y])
    if y+1 <= n-1 and block[x][y+1] == INF:
        block[x][y+1] = block[x][y]+1
        que.append([x, y+1])
    if y-1 >= 0 and block[x][y-1] == INF:
        block[x][y-1] = block[x][y]+1
        que.append([x, y-1])
num = 0
sit = [[1]*n for _ in range(n)]


def bfs(block, sit, xx, yy):
    que = collections.deque([[xx, yy]])
    block[xx][yy] = block[xx][yy]-1
    while que:
        x, y = que.popleft()
        if x+1 <= n-1 and block[x+1][y] > block[x][y]+sit[x+1][y]:
            block[x+1][y] = block[x][y]+sit[x+1][y]
            que.append([x+1, y])
        if x-1 >= 0 and block[x-1][y] > block[x][y]+sit[x-1][y]:
            block[x-1][y] = block[x][y]+sit[x-1][y]
            que.append([x-1, y])
        if y+1 <= n-1 and block[x][y+1] > block[x][y]+sit[x][y+1]:
            block[x][y+1] = block[x][y]+sit[x][y+1]
            que.append([x, y+1])
        if y-1 >= 0 and block[x][y-1] > block[x][y]+sit[x][y-1]:
            block[x][y-1] = block[x][y]+sit[x][y-1]
            que.append([x, y-1])


for x, y in S:
    num += block[x][y]
    sit[x][y] = 0
    bfs(block, sit, x, y)

print(num)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
p = [int(i)-1 for i in input().split()]
c = [[1]*n for _ in range(n)] 
d = [[0]*n for _ in range(n)]
for x in range(n):
    for y in range(n):
        d[y][x] += min(min(x, n-x-1), min(y, n-y-1))
ans = 0
for i in p:
    x, y = i%n, i//n
    c[y][x] = 0
    ans += d[y][x]
    que = deque([[x, y]])
    while que:
        x, y = que.popleft()
        for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
            nx, ny = x+dx, y+dy
            if 0 <=nx< n and 0<=ny<n:
                if d[y][x]+c[y][x]<d[ny][nx]:
                    d[ny][nx] = d[y][x]+c[y][x]
                    que.append([nx, ny])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from random import shuffle
N = int(input())
P = [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)
@numba.njit()
def proc(N, P):
    ans = 0
    Removed = np.zeros((N, N), dtype=np.int32)
    closed = np.zeros((N,N), dtype=np.int32)
    Mat = np.zeros((N, N), dtype=np.int32)
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

    for y in range(N):
        for x in range(N):
            Mat[y, x] = min(y, N-1-y, x, N-1-x)
    #print(Mat)
    for i in range(N*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
                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(N, P)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys

input = sys.stdin.readline
def INT(): return int(input())
def MAP(): return map(int,input().split())
def LI(): return list(map(int,input().split()))

from collections import deque

def main():
    N = INT()
    P = LI()
    adjlist = [[1,1,1,1] for i in range(N**2)]

    def isGoal(node):
        return node//N == 0 or node//N == N-1 or node%N == N-1 or node%N == 0

    output = 0

    for p in P:
        min_cost = 10**9
        queue = deque([(p-1,0)])
        cost_mat = [N]*N**2

        while queue:
            node,cost = queue.popleft()
            if isGoal(node):
                min_cost = cost
                break
            
            if cost >= min_cost or cost_mat[node] <= cost:
                continue

            cost_mat[node] = cost
                        
            for direction in range(4):
                if adjlist[node][direction] == 0:
                    if direction == 0:
                        queue.appendleft((node-N,cost))
                    elif direction == 1:
                        queue.appendleft((node+N,cost))
                    elif direction == 2:
                        queue.appendleft((node-1,cost))
                    else:
                        queue.appendleft((node+1,cost))
                else:
                    if direction == 0:
                        queue.append((node-N,cost+1))
                    elif direction == 1:
                        queue.append((node+N,cost+1))
                    elif direction == 2:
                        queue.append((node-1,cost+1))
                    else:
                        queue.append((node+1,cost+1))
        
        node = p-1
        if node//N > 0:
            adjlist[node-N][1] = 0
        if node//N < N-1:
            adjlist[node+N][0] = 0
        if node%N > 0:
            adjlist[node-1][3] = 0
        if node%N < N-1:
            adjlist[node+1][2] = 0
        
        output += min_cost


    print(output)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
S=list(map(int,input().split()))
count=0
P=[0]*(N*N+1)
for j in range(N*N):
  P[j+1]=S.index(j+1)
for i in range(N*N):
  player=S[i]
  hayasa=P[player]
  
  que=[[] for _ in range(N)]
  d=[-1]*(N*N+1)
  que[0].append(player)
  d[player]=0
  
  j=0
  finish=0
  while True:
    for kouho in que[j]:
      if kouho%N==0:
        finish=1
        break
      if kouho%N==1:
        finish=1
        break
      if kouho+N>N*N:
        finish=1
        break
      if kouho<N:
        finish=1
        break
        
      if d[kouho+N]==-1:
        if P[kouho+N]>hayasa:
          que[j+1].append(kouho+N)
          d[kouho+N]=0
        else:
          que[j].append(kouho+N)
          d[kouho+N]=0
          
      if d[kouho-N]==-1:
        if P[kouho-N]>hayasa:
          que[j+1].append(kouho-N)
          d[kouho-N]=0
        else:
          que[j].append(kouho-N)
          d[kouho-N]=0
          
      if d[kouho+1]==-1:
        if P[kouho+1]>hayasa:
          que[j+1].append(kouho+1)
          d[kouho+1]=0
        else:
          que[j].append(kouho+1)
          d[kouho+1]=0
          
      if d[kouho-1]==-1:
        if P[kouho-1]>hayasa:
          que[j+1].append(kouho-1)
          d[kouho-1]=0
        else:
          que[j].append(kouho-1)
          d[kouho-1]=0
    if finish==1:
      count+=j

Submission status: Time Limit Exceeded

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

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()
	
	
	
if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
import collections
n = int(input())
P = list(map(int, input().split()))
S = []
for p in P:
    p = p-1
    a = p % n
    b = p//n
    S.append([b, a])


INF = float('inf')
que = collections.deque([])
block = [[INF]*n for _ in range(n)]
for i in range(n):
    block[0][i] = 0
    block[n-1][i] = 0
    que.append([0, i])
    que.append([n-1, i])

for i in range(1, n-1):
    block[i][0] = 0
    block[i][n-1] = 0
    que.append([i, 0])
    que.append([i, n-1])

while que:
    x, y = que.popleft()
    if x+1 <= n-1 and block[x+1][y] == INF:
        block[x+1][y] = block[x][y]+1
        que.append([x+1, y])
    if x-1 >= 0 and block[x-1][y] == INF:
        block[x-1][y] = block[x][y]+1
        que.append([x-1, y])
    if y+1 <= n-1 and block[x][y+1] == INF:
        block[x][y+1] = block[x][y]+1
        que.append([x, y+1])
    if y-1 >= 0 and block[x][y-1] == INF:
        block[x][y-1] = block[x][y]+1
        que.append([x, y-1])
num = 0
sit = [[1]*n for _ in range(n)]


def bfs(block, sit, xx, yy):
    que = collections.deque([[xx, yy]])
    block[xx][yy] = block[xx][yy]-1
    while que:
        x, y = que.popleft()
        if x+1 <= n-1 and block[x+1][y] > block[x][y]+sit[x+1][y]:
            block[x+1][y] = block[x][y]+sit[x+1][y]
            que.append([x+1, y])
        if x-1 >= 0 and block[x-1][y] > block[x][y]+sit[x-1][y]:
            block[x-1][y] = block[x][y]+sit[x-1][y]
            que.append([x-1, y])
        if y+1 <= n-1 and block[x][y+1] > block[x][y]+sit[x][y+1]:
            block[x][y+1] = block[x][y]+sit[x][y+1]
            que.append([x, y+1])
        if y-1 >= 0 and block[x][y-1] > block[x][y]+sit[x][y-1]:
            block[x][y-1] = block[x][y]+sit[x][y-1]
            que.append([x, y-1])

    block[xx][yy] = block[xx][yy]


for x, y in S:
    num += block[x][y]
    sit[x][y] = 0
    bfs(block, sit, x, y)

print(num)

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

      for nn in list(n.neighbors):
        nn.neighbors.remove(n)
        nn.neighbors.add(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()