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:
from numba import njit
import numpy as np
@njit
def dfs(v,c,h,stay):
    # hを更新
    todo=[[v,c]]
    while todo:
        vv,cc=todo.pop()
        x,y=divmod(vv,n)
        for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
            nx,ny=x+dx,y+dy
            if 0<=nx<n and 0<=ny<n:
                nv=nx*n+ny
                if h[nv]>cc:
                    h[nv]=cc
                    todo.append([nv,cc+stay[nv]])
                    #dfs(nv,c+stay[nv],h,stay)

@njit
def main(n,p):
    h=[min(i//n,n-i//n-1,i%n,n-i%n-1) for i in range(n**2)]
    h=np.array(h)
    stay=np.full(n**2,1)
    ans=0

    for v in p:
        c=h[v]
        ans+=c
        stay[v]=0
        dfs(v,c,h,stay)
    print(ans)

    #for i in range(n):
    #    print(h[i*n:(i+1)*n])
if __name__=='__main__':
    n=int(input())
    p=np.array(list(map(int,input().split())),np.int32)
    p-=1
    main(n,p)

Submission status: Time Limit Exceeded

Solution code:
def examA():
    T = I()
    ans = [inf]*T
    for t in range(T):
        N, A, B, C, D = LI()
        num = [[2,A],[3,B],[5,C]]
        dp = defaultdict(lambda: inf)
        dp[N] = 0
        que = deque()
        que.append(N)
        while(que):
            now = que.pop()
            if now==0:
                continue
            cur = dp[now] + D*now
            if cur<dp[0]:
                dp[0] = cur
            cur = dp[now]
            for n,K in num:
                curn = cur + (now % n) * D + K
                if curn < dp[(now - now % n) // n]:
                    dp[(now - now % n) // n] = curn
                    que.append((now - now % n) // n)
                curn_ = cur + (-now % n) * D + K
                if curn_ < dp[(now + (-now % n)) // n]:
                    dp[(now + (-now % n)) // n] = curn_
                    que.append((now + (-now % n)) // n)
        ans[t] = dp[0]
    for v in ans:
        print(v)
    return

def examB():
    N = I()
    P = LI()
    L = [[min(i,j,N+1-i,N+1-j)for i in range(1,N+1)]for j in range(1,N+1)]
    exist = [[1]*N for _ in range(N)]
    cost = 0
    def bfs(s):
        que = deque()
        que.appendleft(s)

        def calc_L(h, w, h1, w1):
            c = L[h][w] + exist[h + h1][w + w1]
            if c < L[h + h1][w + w1]:
                L[h + h1][w + w1] = c
                s1 = (h + h1) * N + (w + w1) + 1
                # print("append",s1)
                que.appendleft(s1)
            return

        while(que):
            now = que.pop()
            h,w = (now-1)//N,(now-1)%N
            if 0<h:
                calc_L(h,w,-1,0)
            if h+1<N:
                calc_L(h,w,1,0)
            if 0<w:
                calc_L(h,w,0,-1)
            if w+1<N:
                calc_L(h,w,0,1)

        return

    #for l in L:
        #print(l)
    #print("start")
    for p in P:
        h,w = (p-1)//N,(p-1)%N
        exist[h][w] = 0
        if 0<L[h][w]:
            L[h][w] -= 1
        bfs(p)
        cost += L[h][w]
        #print(p,cost)
    #for l in exist:
        #print(l)
    ans = cost
    print(ans)
    return

def examB2():
    N = I()
    P = LI()
    L = [min(i,j,N+1-i,N+1-j) for i in range(1,N+1) for j in range(1,N+1)]
    exist = [1]*(N**2)
    cost = 0
    def bfs(s):
        que = deque()
        que.appendleft(s)

        def calc_L(s, s0):
            c = L[s] + exist[s+s0]
            if c < L[s+s0]:
                L[s+s0] = c
                s1 = s+s0
                # print("append",s1)
                que.appendleft(s1)
            return

        while(que):
            now = que.pop()
            if 0<s-1:
                calc_L(h,w,-1,0)
            if h+1<N:
                calc_L(h,w,1,0)
            if 0<w+1:
                calc_L(h,w,0,-1)
            if w+1<N:
                calc_L(h,w,0,1)

        return

    #for l in L:
        #print(l)
    #print("start")
    for p in P:
        h,w = (p-1)//N,(p-1)%N
        exist[h][w] = 0
        if 0<L[h][w]:
            L[h][w] -= 1
        bfs(p)
        cost += L[h][w]
        #print(p,cost)
    #for l in exist:
        #print(l)
    ans = cost
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return


import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examB()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Time Limit Exceeded

Solution code:
def examA():
    T = I()
    ans = [inf]*T
    for t in range(T):
        N, A, B, C, D = LI()
        num = [[2,A],[3,B],[5,C]]
        dp = defaultdict(lambda: inf)
        dp[N] = 0
        que = deque()
        que.append(N)
        while(que):
            now = que.pop()
            if now==0:
                continue
            cur = dp[now] + D*now
            if cur<dp[0]:
                dp[0] = cur
            cur = dp[now]
            for n,K in num:
                curn = cur + (now % n) * D + K
                if curn < dp[(now - now % n) // n]:
                    dp[(now - now % n) // n] = curn
                    que.append((now - now % n) // n)
                curn_ = cur + (-now % n) * D + K
                if curn_ < dp[(now + (-now % n)) // n]:
                    dp[(now + (-now % n)) // n] = curn_
                    que.append((now + (-now % n)) // n)
        ans[t] = dp[0]
    for v in ans:
        print(v)
    return

def examB():
    N = I()
    P = LI()
    L = [[min(i,j,N+1-i,N+1-j)for i in range(1,N+1)]for j in range(1,N+1)]
    exist = [[True]*N for _ in range(N)]
    cost = 0
    def bfs(s):
        que = deque()
        que.appendleft(s)

        def calc_L(h, w, h1, w1):
            c = L[h][w] + exist[h + h1][w + w1]
            if c < L[h + h1][w + w1]:
                L[h + h1][w + w1] = c
                s1 = (h + h1) * N + (w + w1) + 1
                # print("append",s1)
                que.appendleft(s1)
            return

        while(que):
            now = que.pop()
            h,w = (now-1)//N,(now-1)%N
            if 0<h+1:
                calc_L(h,w,-1,0)
            if h+1<N:
                calc_L(h,w,1,0)
            if 0<w+1:
                calc_L(h,w,0,-1)
            if w+1<N:
                calc_L(h,w,0,1)

        return

    #for l in L:
        #print(l)
    #print("start")
    for p in P:
        h,w = (p-1)//N,(p-1)%N
        exist[h][w] = False
        if 0<L[h][w]:
            L[h][w] -= 1
        bfs(p)
        cost += L[h][w]
        #print(p,cost)
    #for l in exist:
        #print(l)
    ans = cost
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return


import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examB()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Time Limit Exceeded

Solution code:
def examA():
    T = I()
    ans = [inf]*T
    for t in range(T):
        N, A, B, C, D = LI()
        num = [[2,A],[3,B],[5,C]]
        dp = defaultdict(lambda: inf)
        dp[N] = 0
        que = deque()
        que.append(N)
        while(que):
            now = que.pop()
            if now==0:
                continue
            cur = dp[now] + D*now
            if cur<dp[0]:
                dp[0] = cur
            cur = dp[now]
            for n,K in num:
                curn = cur + (now % n) * D + K
                if curn < dp[(now - now % n) // n]:
                    dp[(now - now % n) // n] = curn
                    que.append((now - now % n) // n)
                curn_ = cur + (-now % n) * D + K
                if curn_ < dp[(now + (-now % n)) // n]:
                    dp[(now + (-now % n)) // n] = curn_
                    que.append((now + (-now % n)) // n)
        ans[t] = dp[0]
    for v in ans:
        print(v)
    return

def examB():
    N = I()
    P = LI()
    L = [[min(i,j,N+1-i,N+1-j)for i in range(1,N+1)]for j in range(1,N+1)]
    exist = [[True]*N for _ in range(N)]
    cost = 0
    def bfs(s):
        que = deque()
        que.appendleft(s)
        while(que):
            now = que.pop()
            h,w = (now-1)//N,(now-1)%N
            for h1,w1 in [[0,-1],[-1,0],[0,1],[1,0]]:
                if h+h1<0 or N<=h+h1 or w+w1<0 or N<=w+w1:
                    continue
                c = L[h][w] + 1 if exist[h+h1][w+w1] else L[h][w]
                if c<L[h+h1][w+w1]:
                    L[h+h1][w+w1] = c
                    s1 = (h+h1)*N + (w+w1) + 1
                    #print("append",s1)
                    que.appendleft(s1)
        return

    #for l in L:
        #print(l)
    #print("start")
    for p in P:
        h,w = (p-1)//N,(p-1)%N
        exist[h][w] = False
        if 0<L[h][w]:
            L[h][w] -= 1
        bfs(p)
        cost += L[h][w]
        #print(p,cost)
    #for l in exist:
        #print(l)
    ans = cost
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return


import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examB()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int, input().split()))
d = [min(i, n - i - 1, j, n - j - 1) for i in range(n) for j in range(n)]
ans = 0
l = [1] * (n ** 2)
for i in p:
    ans += d[i - 1]
    l[i - 1] = 0
    que = [i - 1]
    while que:
        s = que.pop()
        if not s % n == n - 1:
            if d[s + 1] > d[s] + l[s]:
                que.append(s + 1)
                d[s + 1] = d[s] + l[s]
        if s % n:
            if d[s - 1] > d[s] + l[s]:
                que.append(s - 1)
                d[s - 1] = d[s] + l[s]
        if s >= n:
            if d[s - n] > d[s] + l[s]:
                que.append(s - n)
                d[s - n] = d[s] + l[s]
        if n ** 2 > s + n:
            if d[s + n] > d[s] + l[s]:
                que.append(s + n)
                d[s + n] = d[s] + l[s]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main(N,P):
    A=[-1]*4*N*N
    ad=(1,N,-1,-N)
    for I in range(4*N*N):
        i,j=I//4,I%4
        if 0<=i+ad[j]<N*N:
            A[i*4+j]=i+ad[j]
    X=[0]*N*N
    for i in range(N*N):
        X[i]=min(i//N,N-1-i//N,i%N,N-1-i%N)
    E=[1]*N*N
    a=0
    q=[0]*N*N*N
    l,r=0,0
    for p in P:
        p-=1
        a+=X[p]
        E[p]=0
        q[r]=p
        r+=1
        while l<r:
            i=q[l]
            l+=1
            for j in A[4*i:4*(i+1)]:
                if 0<=j and X[i]+E[i]<X[j]:
                    X[j]=X[i]+E[i]
                    q[r]=j
                    r+=1
    return a
import sys
import numpy as np
readline=sys.stdin.buffer.readline
read=sys.stdin.buffer.read
if sys.argv[-1]=='ONLINE_JUDGE':
    from numba import*
    from numba.pycc import CC
    cc=CC('my_module')
    def cc_export(f,signature):
        cc.export(f.__name__,signature)(f)
        return njit(f)
    main=cc_export(main,(i8,i8[:],))
    cc.compile()
    exit()
N=int(readline())
P=np.array(readline().split(),dtype=np.int64)
from my_module import main
print(main(N,P))

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
P=list(map(int,input().split()))
A=[[x if 0<=x<N*N else -1 for x in (i+1,i+N,i-1,i-N)] for i in range(N*N)]
X=[min(i//N,N-1-i//N,i%N,N-1-i%N) for i in range(N*N)]
E=[1]*N*N
r=0
from collections import deque
q=deque()
for p in P:
    p-=1
    r+=X[p]
    E[p]=0
    q.append(p)
    while q:
        i=q.popleft()
        for j in A[i]:
            if 0<=j and X[i]+E[i]<X[j]:
                X[j]=X[i]+E[i]
                q.append(j)
print(r)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
 
N = int(input())
P = list(map(int,input().split()))
 
MAP = [[min(i, j, N-i-1, N-j-1) for i in range(N)] for j in range(N)]
 
d = [[1 for i in range(N)] for j in range(N)]
 
tx = [1, 0, -1, 0]
ty = [0, 1, 0, -1]
 
ans = 0

q = deque()
 
for p in P:
    x = (p-1) // N
    y = (p-1) % N
    d[x][y] = 0
    
    ans += MAP[x][y]
    
    q.clear()
    
    q.append((x, y))
    
    while len(q) != 0:
        x, y = q.popleft()
        for i in range(4):
            nx = x + tx[i]
            ny = y + ty[i]
            if 0 <= nx < N and 0 <= ny < N and MAP[nx][ny] > MAP[x][y] + d[x][y]:
                MAP[nx][ny] = MAP[x][y] + d[x][y]
                q.append((nx, ny))
 
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

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

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

tx = [1, 0, -1, 0]
ty = [0, 1, 0, -1]

ans = 0

for p in P:
    x = (p-1) // N
    y = (p-1) % N
    d[x][y] = 0
    
    ans += MAP[x][y]
    
    q = deque()
    
    q.append((x, y))
    
    while len(q) != 0:
        x, y = q.popleft()
        for i in range(4):
            nx = x + tx[i]
            ny = y + ty[i]
            if 0 <= nx < N and 0 <= ny < N and MAP[nx][ny] > MAP[x][y] + d[x][y]:
                MAP[nx][ny] = MAP[x][y] + d[x][y]
                q.append((nx, ny))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

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

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

tx = [1, 0, -1, 0]
ty = [0, 1, 0, -1]

ans = 0

for p in P:
    x = (p-1) // N
    y = (p-1) % N
    d[x][y] = 0
    cnt = float('INF')
    for i in range(4):
        nx = x + tx[i]
        ny = y + ty[i]
        if 0 <= nx < N and 0 <= ny < N:
            cnt = min(cnt, MAP[nx][ny] + d[nx][ny])
        else:
            cnt = min(cnt, 0)
    
    ans += MAP[x][y]
    
    MAP[x][y] = cnt
    
    q = deque()
    
    q.append((x, y, cnt))
    
    while len(q) != 0:
        x, y, cnt = q.popleft()
        for i in range(4):
            nx = x + tx[i]
            ny = y + ty[i]
            if 0 <= nx < N and 0 <= ny < N and MAP[nx][ny] > MAP[x][y] + d[x][y]:
                MAP[nx][ny] = MAP[x][y] + d[x][y]
                q.append((nx, ny, cnt + d[x][y]))


print(ans)

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue

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

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

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

tx = [1, 0, -1, 0]
ty = [0, 1, 0, -1]

ans = 0

for p in P:
    x = (p-1) // N
    y = (p-1) % N
    d[x][y] = 0
    cnt = float('INF')
    for i in range(4):
        nx = x + tx[i]
        ny = y + ty[i]
        if 0 <= nx < N and 0 <= ny < N:
            cnt = min(cnt, MAP[nx][ny] + d[nx][ny])
        else:
            cnt = min(cnt, 0)
    
    ans += MAP[x][y]
    
    MAP[x][y] = cnt
    
    q = Queue()
    
    q.put((x, y, cnt))
    
    while not q.empty():
        x, y, cnt = q.get()
        for i in range(4):
            nx = x + tx[i]
            ny = y + ty[i]
            if 0 <= nx < N and 0 <= ny < N and MAP[nx][ny] > MAP[x][y] + d[x][y]:
                MAP[nx][ny] = MAP[x][y] + d[x][y]
                q.put((nx, ny, cnt + d[x][y]))
    

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(4100000)

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

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

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

tx = [1, 0, -1, 0]
ty = [0, 1, 0, -1]

def dfs(x, y, cnt):
    for i in range(4):
        nx = x + tx[i]
        ny = y + ty[i]
        if 0 <= nx < N and 0 <= ny < N and MAP[nx][ny] > MAP[x][y] + d[x][y]:
            MAP[nx][ny] = MAP[x][y] + d[x][y]
            dfs(nx, ny, cnt + d[x][y])

ans = 0

for p in P:
    x = (p-1) // N
    y = (p-1) % N
    d[x][y] = 0
    cnt = float('INF')
    for i in range(4):
        nx = x + tx[i]
        ny = y + ty[i]
        if 0 <= nx < N and 0 <= ny < N:
            cnt = min(cnt, MAP[nx][ny] + d[nx][ny])
        else:
            cnt = min(cnt, 0)
    
    ans += MAP[x][y]
    
    MAP[x][y] = cnt
    
    dfs(x, y, cnt)
    

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
import time
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
#    n = 500
    cos = [min(i//n,n-1-i//n,i%n,n-1-i%n) for i in range(n**2)]
#    p = [i for i in range(n**2)]
    p = [int(i)-1 for i in ipt().split()]
    ans = 0
    hq = []
    dr = [-1,-n,1,n]
    al = [False]*(n**2)

    for pi in p:
        ans += cos[pi]
        hpq.heappush(hq,(cos[pi],pi))
        al[pi] = True
        while hq:
            qc,qi = hpq.heappop(hq)
            ad = qc if al[qi] else qc+1
            for d in dr:
                if 0 <= d+qi < n**2 and cos[d+qi] > ad:
                    hpq.heappush(hq,(ad,d+qi))
                    cos[d+qi] = ad
    print(ans)

    return

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
import time
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
#    n = 500
    cos = [min(i//n,n-1-i//n,i%n,n-1-i%n) for i in range(n**2)]
#    p = [i for i in range(n**2)]
    p = [int(i)-1 for i in ipt().split()]
    ans = 0
    hq = []
    dr = [-1,-n,1,n]
    al = [False]*(n**2)

    for pi in p:
        ans += cos[pi]
        hpq.heappush(hq,(cos[pi],pi))
        al[pi] = True
        while hq:
            qc,qi = hpq.heappop(hq)
            ad = 0 if al[qi] else 1
            for d in dr:
                if 0 <= d+qi < n**2 and cos[d+qi] > qc+ad:
                    hpq.heappush(hq,(qc+ad,d+qi))
                    cos[d+qi] = qc+ad
    print(ans)

    return

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n = I()
P = LI()
L = [[min(x, y, n - x - 1, n - y - 1) for x in range(n)] for y in range(n)]
flg = [[1] * n for _ in range(n)]
ans = 0
for i in P:
    xi = (i - 1) % n
    yi = (i - 1) // n
    ans += L[yi][xi]
    flg[yi][xi] = 0
    q = [((i - 1) // n,  (i - 1) % n)]
    while q:
        a, b = q.pop()
        val = L[a][b] + flg[a][b]
        for j, k in ((0, 1), (1, 0), (-1, 0), (0, -1)):
            ai, bi = a + j, b + k
            if 0 <= ai < n and 0 <= bi < n and L[ai][bi] > val:
                L[ai][bi] = val
                q += [(ai, bi)]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n = I()
P = LI()
L = [[min(x, y, n - x - 1, n - y - 1) for x in range(n)] for y in range(n)]
flg = [[1] * n for _ in range(n)]
ans = 0
for i in P:
    xi = (i - 1) % n
    yi = (i - 1) // n
    ans += L[yi][xi]
    flg[yi][xi] = 0
    q = [((i - 1) // n,  (i - 1) % n)]
    while q:
        a, b = q.pop()
        for j, k in ((0, 1), (1, 0), (-1, 0), (0, -1)):
            ai, bi = a + j, b + k
            if 0 <= ai < n and 0 <= bi < n and L[ai][bi] > L[a][b] + flg[a][b]:
                L[ai][bi] = L[a][b] + flg[a][b]
                q += [(ai, bi)]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
import pprint
import numpy as np
from heapq import heappush, heappop
N = int(input())
PS = [int(x) for x in input().split()]


person = [1] * (N * N)


def search(start):
    to_visit = [start]
    next_visit = []
    visited = [0] * (N * N)
    cost = 0
    while to_visit:
        while to_visit:
            p = to_visit.pop()
            if visited[p]:
                continue
            visited[p] = 1

            y, x = divmod(p, N)
            if x == 0 or x == (N - 1) or y == 0 or y == (N - 1):
                return cost
            for d in (-1, +1, -N, +N):
                if person[p + d]:
                    next_visit.append(p + d)
                else:
                    to_visit.append(p + d)
        to_visit = next_visit
        next_visit = []
        cost += 1


total_cost = 0
for p in PS:
    # print(p)
    p -= 1  # 0-origin
    total_cost += search(p)
    person[p] = 0
    # print("t", total_cost)

print(total_cost)

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
sys.setrecursionlimit(100000)

def main(n,p,dx,dy):
    ans = 0
    def dfs(x,y,dx,dy,grid,dis):
        z = dis[y][x] + grid[y][x]
        for i in range(4):
            next_x = x+dx[i]
            next_y = y+dy[i]
            if dis[next_y][next_x] > z:
                dis[next_y][next_x] = z
                dfs(next_x,next_y,dx,dy,grid,dis)
    grid = np.ones((n+1,n+1),np.int32)
    dis = np.zeros((n+2,n+2),np.int32)
    for i in range(1,n+1):
        for j in range(1,n+1):
            dis[i][j] = min(i,n-i+1,j,n-j+1)-1
    for i in range(n**2):
        pos = p[i]
        x = (pos-1)%n+1
        y = (pos-1)//n+1
        ans += dis[y][x]
        grid[y][x] = 0
        dfs(x,y,dx,dy,grid,dis)
    return ans

n = int(readline())
p = np.array(readline().split(),np.int32)
dx = np.array([0,1,0,-1])
dy = np.array([1,0,-1,0])
print(main(n,p,dx,dy))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(100000)

def main(n,p):
    dx = np.array([0,1,0,-1])
    dy = np.array([1,0,-1,0])
    ans = 0
    def dfs(x,y,dx,dy,grid,dis):
        z = dis[y][x] + grid[y][x]
        for i in range(4):
            next_x = x+dx[i]
            next_y = y+dy[i]
            if dis[next_y][next_x] > z:
                dis[next_y][next_x] = z
                dfs(next_x,next_y,dx,dy,grid,dis)
    grid = np.ones((n+1,n+1),np.int32)
    dis = np.zeros((n+2,n+2),np.int32)
    for i in range(1,n+1):
        for j in range(1,n+1):
            dis[i][j] = min(i,n-i+1,j,n-j+1)-1
    for i in range(n**2):
        pos = p[i]
        x = (pos-1)%n+1
        y = (pos-1)//n+1
        ans += dis[y][x]
        grid[y][x] = 0
        dfs(x,y,dx,dy,grid,dis)
    return ans

n = int(readline())
p = np.array(readline().split(),np.int32)
print(main(n,p))

Submission status: Time Limit Exceeded

Solution code:
import copy

def fillDistanceTable(PersonMap, DistanceMap, n, shortest, target, index):
    if shortest > n * n:
        print("Error")
        exit()
    if DistanceMap[target] > n * n:
        flag = False
        for i in range(n * n):
            if DistanceMap[i] > n * n:
                if DistanceMap[ i - 1 ] <= shortest or DistanceMap[ i + 1 ] <= shortest or DistanceMap[ i - n ] <= shortest or DistanceMap[ i + n ] <= shortest:
                    setDistance(PersonMap, DistanceMap, i, shortest, index)
                    flag = True
        if flag:
            fillDistanceTable(PersonMap, DistanceMap, n, shortest, target, index)
        else:
            fillDistanceTable(PersonMap, DistanceMap, n, shortest + 1, target, index)
        
def setDistance(PersonMap, DistanceMap, i, dist, index):
    if PersonMap[i] > index:
        DistanceMap[i] = dist + 1
    else:
        DistanceMap[i] = dist

def checkBestRoot(PersonMap, n, target, index):
    DistanceMap =  [n * n + 1] * (n * n)
    for i in range(n):
        setDistance(PersonMap, DistanceMap, i, 0, index)
        setDistance(PersonMap, DistanceMap, n * n - n + i, 0, index)
        setDistance(PersonMap, DistanceMap, n * i, 0, index)
        setDistance(PersonMap, DistanceMap, n * i + n - 1, 0, index)
    fillDistanceTable(PersonMap, DistanceMap, n, 0, target, index)
    return DistanceMap[target]

def main():
    ans = 0
    n = int(input())
    seq = list(map(int,input().split()))
    PersonMap = [0] * (n * n)
    for i in range(n*n):
        PersonMap[seq[i] - 1] = i

    for i in range(n*n):
        ans = ans + checkBestRoot(PersonMap, n, seq[i] - 1, i)

    print(ans)

main()