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 collections import deque
import heapq

N = int(input())
S = list(map(int, input().split()))
P = [0]*(N**2)
for i in range(N**2):
    P[S[i]-1] = i

def bfs(loc):
    data = [-1]*(N**2)
    data[loc] = 1
    ans = N**2
    s = P[loc]
    stack = [[0, loc]]
    while stack:
        d, v = heapq.heappop(stack)
        # 上
        if v-N >= 0:
            if data[v-N] == -1:
                data[v-N] = 1
                if s < P[v-N]:
                    heapq.heappush(stack, [d+1, v-N])
                else:
                    heapq.heappush(stack, [d, v-N])
        else:
            return d
            # ans = min(ans, d)
        # 左
        if v%N != 0:
            if data[v-1] == -1:
                data[v-1] = 1
                if s < P[v-1]:
                    heapq.heappush(stack, [d+1, v-1])
                else:
                    heapq.heappush(stack, [d, v-1])
        else:
            return d
            # ans = min(ans, d)
        # 右
        if (v+1)%N != 0 and v != N**2-1:
            if data[v+1] == -1:
                data[v+1] = 1
                if s < P[v+1]:
                    heapq.heappush(stack, [d+1, v+1])
                else:
                    heapq.heappush(stack, [d, v+1])
        else:
            return d
            # ans = min(ans, d)
        # 下
        if v+N < N**2:
            if data[v+N] == -1:
                data[v+N] = 1
                if s < P[v+N]:
                    heapq.heappush(stack, [d+1, v+N])
                else:
                    heapq.heappush(stack, [d, v+N])
        else:
            return d
            # ans = min(ans, d)
    return ans

ans = 0
for i in range(N**2):
    ans += bfs(i)
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:
from heapq import heappush, heappop

n = int(input())
p = list(map(int, input().split()))

rev_p = [0] * (n * n)
for offset in range(len(p)):
    rev_p[p[offset] - 1] = offset

ans = 0
for i, pi in enumerate(p):
    h = []
    heappush(h, (0, pi-1))
    memo = set()

    while h:
        cost, pos = heappop(h)

        if pos in memo:
            continue

        memo.add(pos)

        if pos < n or pos >= n * (n-1) or pos % n == 0 or pos % n == n-1:
            ans += cost
            break

        for offset in [-1, -n, 1, n]:
            if 0 <= pos + offset < n * n:
                if rev_p[pos + offset] < i:
                    heappush(h, (cost, pos + offset))
                else:
                    heappush(h, (cost + 1, pos + offset))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def hate(x,y):
    cur_hate = 0
    cur_q = deque()
    next_q = deque()
    cur_q.append((x,y))
    already = set()
    while True:
        while cur_q:
            x,y = cur_q.popleft()
            for i in range(4):
                next_x = x+dx[i]
                next_y = y+dy[i]
                if not (next_x,next_y) in already:
                    if grid[next_y][next_x] == "o":
                        if cur_hate == 0:
                            for x,y in already:
                                grid[y][x] = "o"
                        return cur_hate
                    if grid[next_y][next_x] == "#":
                        next_q.append((next_x,next_y))
                    else:
                        cur_q.append((next_x,next_y))
                    already.add((x,y))
        cur_hate += 1
        cur_q = next_q
        next_q = deque()
n = int(input())
grid = []
grid.append(["o"]*(n+2))
for i in range(n):
    grid.append(["o"]+["#"]*n+["o"])
grid.append(["o"]*(n+2))
dx = [0,1,0,-1]
dy = [1,0,-1,0]
ans = 0
p = list(map(int,input().split()))
for i in range(n**2):
    pos = p[i]
    x = (pos-1)%n+1
    y = (pos-1)//n+1
    h = hate(x,y)
    ans += h
    if h == 0:
        grid[y][x] = "o"
    else:
        grid[y][x] = "."
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
orderstring = input()
ordercopy = orderstring.split(" ")
order = [0]*n
index = 0
while index < n:
    order[index] = int(ordercopy[index])
seat = [["occupied" for i in range(n)] for j in range(n)]
hated = 0
i = 0
while i < len(order):
    col = order[i] % n - 1
    row = (order[i] - col) / n - 1
    area = [["no" for i in range(n)] for j in range(n)]
    area[row][col] = "yes"
    times = 0
    judge = 0
    while times < 500:
        r = 0
        c = 0
        while 0 < r and r < n - 1:
            while 0 < c and c < n - 1:
                if area[r][c] == "yes" and seat[r-1][c]=="empty":
                    area[r-1][c] = "yes"
                if area[r][c] == "yes" and seat[r][c-1]=="empty":
                    area[r][c-1] = "yes"
                if area[r][c] == "yes" and seat[r+1][c]=="empty":
                    area[r+1][c] = "yes"
                if area[r][c] == "yes" and seat[r][c+1]=="empty":
                    area[r][c+1] = "yes"
                c+= 1
            r+=1
        times+=1
    test = 0
    while test < n:
        if area[0][test] == "yes":
            judge = 1
        test+=1
    test = 0
    while test < n:
        if area[n-1][test] == "yes":
            judge = 1
        test+=1
    test = 0
    while test < n:
        if area[test][0] == "yes":
            judge = 1
        test+=1
    while test < n:
        if area[test][n-1] == "yes":
            judge = 1
        test+=1
    if judge == 0:
        hated+=1
    i+=1
print(hated)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N=int(input())
    P=tuple(map(int1,input().split()))
    c=[[1]*N for _ in range(N)]
    ans=0
    dy,dx=[1,0,-1,0],[0,1,0,-1]
    prev_y,prev_x=-1,-1
    for p in P:
        que=deque([(p//N,p%N)])
        d=[[INF]*N for _ in range(N)]
        d[p//N][p%N]=0
        f=True
        while que and f:
            y,x=que.popleft()
            if y==prev_y and x==prev_x:
                tmp=d[y][x]+prev_d[prev_y][prev_x]
                break
            for k in range(4):
                ny,nx=(y+dy[k],x+dx[k])
                if 0<=ny<N and 0<=nx<N:
                    if d[ny][nx]==INF:
                        if c[ny][nx]==1:
                            d[ny][nx]=d[y][x]+1
                            que.append((ny,nx))
                        else:
                            d[ny][nx]=d[y][x]
                            que.appendleft((ny,nx))
                else:
                    tmp=d[y][x]
                    f=False
                    break
        ans+=tmp
        c[p//N][p%N]=0
        prev_d=[l[:] for l in d]
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())
P = list(map(int, input().split()))
grid = [[1]*N for _ in range(N)]
c = [[min(i, N-1-i, j, N-1-j) for i in range(N)] for j in range(N)]
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

ans = 0
for pi in P:
  pi -= 1
  hi = pi//N
  wi = pi%N
  ans += c[hi][wi]
  grid[hi][wi] = 0
  stack = deque([[hi, wi]])
  while stack:
    nowy, nowx = stack.pop()
    for dxi, dyi in zip(dx, dy):
      nxy = nowy + dyi
      nxx = nowx + dxi
      if (nxy==-1) or (nxy==N) or (nxx==-1) or (nxx==N):
        continue
      if c[nxy][nxx] == 0:
        continue
      if grid[nowy][nowx] == 0:
        if c[nxy][nxx] > c[nowy][nowx]:
          c[nxy][nxx] = c[nowy][nowx]
          stack.append([nxy, nxx])
      else:
        if c[nxy][nxx] > c[nowy][nowx]+1:
          c[nxy][nxx] = c[nowy][nowx]+1
          stack.append([nxy, nxx])
          

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def hate(x,y):
    cur_hate = 0
    cur_q = deque()
    next_q = deque()
    cur_q.append((x,y))
    already = set()
    while True:
        while cur_q:
            x,y = cur_q.popleft()
            for i in range(4):
                next_x = x+dx[i]
                next_y = y+dy[i]
                if not (next_x,next_y) in already:
                    if grid[next_y][next_x] == "o":
                        return cur_hate
                    if grid[next_y][next_x] == "#":
                        next_q.append((next_x,next_y))
                    else:
                        cur_q.append((next_x,next_y))
                    already.add((x,y))
        cur_hate += 1
        cur_q = next_q
        next_q = deque()
n = int(input())
grid = []
grid.append(["o"]*(n+2))
for i in range(n):
    grid.append(["o"]+["#"]*n+["o"])
grid.append(["o"]*(n+2))
dx = [0,1,0,-1]
dy = [1,0,-1,0]
ans = 0
p = list(map(int,input().split()))
for i in range(n**2):
    pos = p[i]
    x = (pos-1)%n+1
    y = (pos-1)//n+1
    ans += hate(x,y)
    if hate(x,y) == 0:
        grid[y][x] = "o"
    else:
        grid[y][x] = "."
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def hate(x,y):
    cur_hate = 0
    cur_q = deque()
    next_q = deque()
    cur_q.append((x,y))
    already = set()
    while True:
        while cur_q:
            x,y = cur_q.popleft()
            for i in range(4):
                next_x = x+dx[i]
                next_y = y+dy[i]
                if not (next_x,next_y) in already:
                    if grid[next_y][next_x] == "o":
                        return cur_hate
                    if grid[next_y][next_x] == "#":
                        next_q.append((next_x,next_y))
                    else:
                        cur_q.append((next_x,next_y))
                    already.add((x,y))
        cur_hate += 1
        cur_q = next_q
        next_q = deque()
n = int(input())
grid = []
grid.append(["o"]*(n+2))
for i in range(n):
    grid.append(["o"]+["#"]*n+["o"])
grid.append(["o"]*(n+2))
dx = [0,1,0,-1]
dy = [1,0,-1,0]
ans = 0
p = list(map(int,input().split()))
for i in range(n**2):
    pos = p[i]
    x = (pos-1)%n+1
    y = (pos-1)//n+1
    ans += hate(x,y)
    grid[y][x] = "."
print(ans)

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)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
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:
        x=heapq.heappop(pq)
        node,mini_dis=x[1],x[0]
        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

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
 ##   print(dijkstra(0,graph,N**2)[some])
    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)

Submission status: Time Limit Exceeded

Solution code:

import queue
N = int(input())
aa = list(map(int, input().split()))


mm = [[0] * N for _ in range(N)]


for i in range((N + 1) // 2):
    j = N - i - 1

    for x in range(i, j + 1):
        mm[i][x] = i
        mm[j][x] = i
        mm[x][i] = i
        mm[x][j] = i


def pm():
    for m in mm:
        print(m)


is_none = [[False] * N for _ in range(N)]

ans = 0

for a in aa:
    x = (a - 1) % N
    y = (a - 1) // N

    # print(x, y)

    ans += mm[y][x]

    is_none[y][x] = True

    mm[y][x] -= 1

    q = queue.Queue()
    q.put((x, y, mm[y][x]))
    while not q.empty():
        x0, y0, n = q.get()

        xx = [x0, x0, x0 + 1, x0 - 1]
        yy = [y0 + 1, y0 - 1, y0, y0]
        for x, y in zip(xx, yy):
            if x < 0 or N <= x or y < 0 or N <= y:
                continue

            if is_none[y][x]:
                if mm[y][x] > n:
                    mm[y][x] = n
                    q.put((x, y, mm[y][x]))
            else:
                if mm[y][x] > n + 1:
                    mm[y][x] = n + 1
                    q.put((x, y, mm[y][x]))

    # pm()


print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N=int(input())
    P=tuple(map(int1,input().split()))
    c=[[1]*N for _ in range(N)]
    ans=0
    dy,dx=[1,0,-1,0],[0,1,0,-1]
    for p in P:
        que=deque([(p//N,p%N)])
        d=[[INF]*N for _ in range(N)]
        d[p//N][p%N]=0
        f=True
        while que and f:
            y,x=que.popleft()
            for k in range(4):
                ny,nx=(y+dy[k],x+dx[k])
                if 0<=ny<N and 0<=nx<N:
                    if d[ny][nx]==INF:
                        if c[ny][nx]==1:
                            d[ny][nx]=d[y][x]+1
                            que.append((ny,nx))
                        else:
                            d[ny][nx]=d[y][x]
                            que.appendleft((ny,nx))
                else:
                    tmp=d[y][x]
                    f=False
                    break
        ans+=tmp
        c[p//N][p%N]=0
    print(ans)

if __name__ == '__main__':
    main()

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())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
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 = defaultdict(lambda: 1)
    ans = 0
    for pi in p:
        y, x = divmod(pi - 1, n)
        ans += dp[y][x]
        c[(y, x)] = 0
        q = deque()
        q.append((y, x))
        while q:
            y, x = q.popleft()
            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
                        if c[(my, mx)]:
                            q.append((my, mx))
                        else:
                            q.appendleft((my, mx))
    print(ans)
    return


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

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 + 1)]
DD = [[-1,0],[1,0],[0,1],[0,-1]]
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, 1])

for i in range(n**2):
    x = i//n
    y = i%n
    if x == 0 or x == n-1 or y == 0 or y == n-1:
        M[i].append([n**2, 0])

# print(M)

ans = 0
import heapq
nn = len(M)
for ii in range(n**2):
    s = P[ii]

    D = [10**9] * nn  # 頂点0からの距離
    # P = [-1] * n  # 頂点0からの最短距離において、そこの直前の頂点(経路復元に利用)
    D[s] = 0
    V = [0] * nn  # その頂点のD[i]が最短距離と確定したら1
    Q = []  # 優先度付きキュー
    # for v in range(nn):
    #     heapq.heappush(Q, [D[v], v])
    heapq.heappush(Q, [D[s], s])

    le = len(Q)
    while len(Q) > 0:
        # print(Q,D)
        q = heapq.heappop(Q)
        u = q[1]
        du = q[0]
        if V[u] == 0:
            V[u] = 1
            le -= 1
            for i in range(len(M[u])):
                v = M[u][i][0]
                luv = M[u][i][1]
                if V[v] == 0:
                    alt = du + luv
                    if D[v] > alt:
                        D[v] = alt
                        # P[v] = u
                        heapq.heappush(Q, [alt, v])

    ans += D[n**2]
    # print(ans)
    # print(P,n)
    x = P[ii]//n
    y = P[ii]%n
    # print(P,P[ii],x,y)
    for d in range(4):
        gx = x + DD[d][0]
        gy = y + DD[d][1]
        # print(gx,gy)
        if 0 <= gx < n and 0 <= gy < n:
            g = gx*n + gy
            # print("g",g)
            for j in range(len(M[g])):
                if M[g][j][0] == P[ii]:
                    M[g][j][1] = 0
                    # print("ok")

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
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())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
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 = defaultdict(lambda: 1)
    ans = 0
    for pi in p:
        y, x = divmod(pi - 1, n)
        ans += dp[y][x]
        c[(y, x)] = 0
        q = []
        q.append((dp[y][x], y, x))
        while q:
            score, y, x = heappop(q)
            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
                        heappush(q, (score + c[(my, mx)], my, mx))
    print(ans)
    return


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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N=int(input())
    P=tuple(map(int1,input().split()))
    c=[[1]*N for _ in range(N)]
    ans=0
    dy,dx=[1,0,-1,0],[0,1,0,-1]
    for p in P:
        que=deque([(p//N,p%N)])
        d=[[INF]*N for _ in range(N)]
        d[p//N][p%N]=0
        tmp=INF
        while que:
            y,x=que.popleft()
            for k in range(4):
                ny,nx=(y+dy[k],x+dx[k])
                if 0<=ny<N and 0<=nx<N:
                    if d[ny][nx]==INF:
                        if c[ny][nx]==1:
                            d[ny][nx]=d[y][x]+1
                            que.append((ny,nx))
                        else:
                            d[ny][nx]=d[y][x]
                            que.appendleft((ny,nx))
                else:
                    tmp=min(tmp,d[y][x])
        ans+=tmp
        c[p//N][p%N]=0
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
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())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
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 = defaultdict(lambda: 1)
    ans = 0
    for pi in p:
        y, x = divmod(pi - 1, n)
        ans += dp[y][x]
        c[(y, x)] = 0
        q = []
        q.append((dp[y][x], y, x))
        while q:
            score, y, x = heappop(q)
            for my, mx in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
                my += y
                mx += x
                if 0 <= my < n and 0 <= mx < n:
                    if dp[my][mx] > score:
                        dp[my][mx] = score
                        heappush(q, (score + c[(my, mx)], my, mx))
    print(ans)
    return


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

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 + 1)]
DD = [[-1,0],[1,0],[0,1],[0,-1]]
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, 1])

for i in range(n**2):
    x = i//n
    y = i%n
    if x == 0 or x == n-1 or y == 0 or y == n-1:
        M[i].append([n**2, 0])

# print(M)

ans = 0
import heapq
nn = len(M)
for ii in range(n**2):
    s = P[ii]

    D = [10**9] * nn  # 頂点0からの距離
    # P = [-1] * n  # 頂点0からの最短距離において、そこの直前の頂点(経路復元に利用)
    D[s] = 0
    V = [0] * nn  # その頂点のD[i]が最短距離と確定したら1
    Q = []  # 優先度付きキュー
    for v in range(nn):
        heapq.heappush(Q, [D[v], v])

    le = len(Q)
    while le > 0:
        q = heapq.heappop(Q)
        u = q[1]
        du = q[0]
        if V[u] == 0:
            V[u] = 1
            le -= 1
            for i in range(len(M[u])):
                v = M[u][i][0]
                luv = M[u][i][1]
                if V[v] == 0:
                    alt = du + luv
                    if D[v] > alt:
                        D[v] = alt
                        # P[v] = u
                        heapq.heappush(Q, [alt, v])

    ans += D[n**2]
    # print(ans)
    # print(P,n)
    x = P[ii]//n
    y = P[ii]%n
    # print(P,P[ii],x,y)
    for d in range(4):
        gx = x + DD[d][0]
        gy = y + DD[d][1]
        # print(gx,gy)
        if 0 <= gx < n and 0 <= gy < n:
            g = gx*n + gy
            # print("g",g)
            for j in range(len(M[g])):
                if M[g][j][0] == P[ii]:
                    M[g][j][1] = 0
                    # print("ok")

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
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())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
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 = defaultdict(lambda: 1)
    ans = 0
    for pi in p:
        y, x = divmod(pi - 1, n)
        ans += dp[y][x]
        c[(y, x)] = 0
        q = []
        q.append((dp[y][x], y, x))
        while q:
            s, y, x = heappop(q)
            score = dp[y][x] + c[(y, x)]
            for my, mx in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
                my += y
                mx += x
                if 0 <= my < n and 0 <= mx < n:
                    if dp[my][mx] > score:
                        dp[my][mx] = score
                        heappush(q, (score, my, mx))
    print(ans)
    return


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

Submission status: Accepted

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

for i in range(n*n):p[i]-=1
seats=[min(i//n,i%n,n-(i//n)-1,n-(i%n)-1) for i in range(n*n)] 

exist=[1]*(n*n)
dxy=(n,-n,1,-1)

ans=0
q=deque()
for pi in p:
    ans+=seats[pi]
    exist[pi]=0
    q.append(pi)
    while q:
        i=q.popleft()
        for dx in dxy:
            idx=i+dx
            if 0<=idx<n*n :
                if seats[i]+exist[i]<seats[idx]:
                    seats[idx]=seats[i]+exist[i]
                    q.append(idx)
print(ans)