Problem:


Score : 700 points

Problem Statement

Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2.

At the end of the movie, the viewers go out of the cinema in a certain order: the i-th viewer leaving her seat is the one denoted by the number P_i. The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat.
To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column).
While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.

Compute the number of pairs of viewers (x, y) such that y will hate x forever.

Constraints

2 \le N \le 500

The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \{1, 2, \dots, N^2\}.

Input

The input is given from Standard Input in the format

N
P_1 P_2 \cdots P_{N^2}

Output

If ans is the number of pairs of viewers described in the statement, you should print on Standard Output

ans

Sample Input 1

3
1 3 7 9 5 4 8 6 2

Sample Output 1

1

Before the end of the movie, the viewers are arranged in the cinema as follows:

1 2 3
4 5 6
7 8 9

The first four viewers leaving the cinema (1, 3, 7, 9) can leave the cinema without going through any seat, so they will not be hated by anybody.

Then, viewer 5 must go through one of the seats where viewers 2, 4, 6, 8 are currently seated while leaving the cinema; hence he will be hated by at least one of those viewers.

Finally the remaining viewers can leave the cinema (in the order 4, 8, 6, 2) without going through any occupied seat (actually, they can leave the cinema without going through any seat at all).

Sample Input 2

4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8

Sample Output 2

3

Sample Input 3

6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30

Sample Output 3

11



Sample input:
3
1 3 7 9 5 4 8 6 2


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

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

distance = [[min(i, j, n - i - 1, n - j - 1) for i in range(n)] for j in range(n)]
check = [[1] * n for i in range(n)]
p = [((i - 1) // n, (i - 1) % n) for i in p]
ans = 0
for i, j in p:
    ans += distance[j][i]
    d=[]
    d.append((j ,i ,distance[j][i]))
    check[j][i] = 0
    while len(d):
        x, y, dis = d.pop()
        for i in range(0, 4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

            if 0 <= nx < n and 0 <= ny < n:
                # 更新できるマスは更新
                if distance[nx][ny] > dis:
                    distance[nx][ny] = dis
                    d.append((nx, ny, dis + check[nx][ny]))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from _collections import deque
N = int(input())
P = list(map(int,input().split()))
K = [( (i-1)//N, (i-1) % N ) for i in P]
used = [[1]*N for _ in range(N)]
C = [[min([i, N-i-1, j, N-j-1]) for j in range(N)] for i in range(N)]

ans = 0
move = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(N*N):
    a,b = K[i]
    used[a][b] = 0
    ans += C[a][b]
    q = deque([[a, b]])
    while(len(q)>0):
        s,t = q.popleft()
        for j,k in move:
            after_s = s+j
            after_t = t+k
            if 0 <= after_s <= N-1:
                if 0 <= after_t <= N-1:
                    c = C[s][t]
                    if used[s][t] == 1:
                        c += 1
                    if c < C[after_s][after_t]:
                        C[after_s][after_t] = c
                        q.append([after_s, after_t])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from _collections import deque
N = int(input())
P = list(map(int,input().split()))
K = []
used = [[1]*N for _ in range(N)]

for i in range(N*N):
    K.append([(P[i]-1)//N, (P[i]-1) % N])

C = {}
for i in range(N):
    for j in range(N):
        C[(i,j)] = min([i, N-i-1, j, N-j-1])

ans = 0
move = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(N*N):
    a,b = K[i]
    used[a][b] = 0
    ans += C[(a,b)]
    q = deque([[a, b]])
    while(len(q)>0):
        s,t = q.popleft()
        for j,k in move:
            after_s = s+j
            after_t = t+k
            if 0 <= after_s <= N-1:
                if 0 <= after_t <= N-1:
                    c = C[(s,t)]
                    if used[s][t] == 1:
                        c += 1
                    if c < C[(after_s, after_t)]:
                        C[(after_s, after_t)] = c
                        q.append([after_s, after_t])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    from collections import deque

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

    distance = [[min(i, j, n - i - 1, n - j - 1) for i in range(n)] for j in range(n)]
    check = [[1] * n for i in range(n)]
    p = [((i - 1) // n, (i - 1) % n) for i in p]
    ans = 0
    for i, j in p:
        ans += distance[j][i]
        d = deque()
        d.append((j, i, distance[j][i]))
        check[j][i] = 0
        while len(d):
            x, y, dis = d.popleft()
            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

                if 0 <= nx < n and 0 <= ny < n:
                    # 更新できるマスは更新
                    if distance[nx][ny] > dis:
                        distance[nx][ny] = dis
                        d.append((nx, ny, dis + check[nx][ny]))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque

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




distance = [[min(i, j, n - i - 1, n - j - 1) for i in range(n)] for j in range(n)]
check = [[1] * n for i in range(n)]
p = [((i-1)//n, (i-1) % n) for i in p]
ans=0
for i,j in p:
    ans+=distance[j][i]
    d = deque()
    d.append((j, i, distance[j][i]))
    check[j][i] = 0
    while len(d):
        x, y, dis = d.popleft()
        for i in range(0, 4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

            if 0 <= nx < n and 0 <= ny < n:
                # 更新できるマスは更新
                if distance[nx][ny] > dis:
                    distance[nx][ny] = dis
                    d.append((nx, ny, dis + check[nx][ny]))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque

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


# 迷路　BFS
def bfs(sx, sy):
    d = deque()
    d.append((sx, sy, distance[sx][sy]))
    check[sx][sy] = 0

    while len(d):
        x, y, dis = d.popleft()
        for i in range(0, 4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

            if 0 <= nx < n and 0 <= ny < n:
                # 更新できるマスは更新
                if distance[nx][ny] > dis:
                    distance[nx][ny] = dis
                    d.append((nx, ny, dis + check[nx][ny]))



distance = [[min(i, j, n - i - 1, n - j - 1) for i in range(n)] for j in range(n)]
check = [[1] * n for i in range(n)]
p = [((i-1)//n, (i-1) % n) for i in p]
ans=0
for i,j in p:
    ans+=distance[j][i]
    bfs(j, i)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque

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


# 迷路　BFS
def bfs(sx, sy):
    d = deque()
    d.append((sx, sy, distance[sx][sy]))
    ans = distance[sx][sy]
    v = distance[sx][sy]
    check[sx][sy] = 0

    while len(d):
        x, y, dis = d.popleft()
        for i in range(0, 4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

            if 0 <= nx < n and 0 <= ny < n:
                # 更新できるマスは更新
                if distance[nx][ny] > dis:
                    distance[nx][ny] = dis
                    d.append((nx, ny, dis + check[nx][ny]))

    return ans

distance = [[min(i, j, n - i - 1, n - j - 1) for i in range(n)] for j in range(n)]
check = [[1] * n for i in range(n)]
p = [((i-1)//n, (i-1) % n) for i in p]
anss=0
for i,j in p:
    anss+=bfs(j, i)

print(anss)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque

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


# 迷路　BFS
def bfs(sx, sy):
    d = deque()
    d.append((sx, sy, distance[sx][sy]))
    ans = distance[sx][sy]
    v = distance[sx][sy]
    check[sx][sy] = 0

    while len(d):
        x, y, dis = d.popleft()
        for i in range(0, 4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

            if 0 <= nx < n and 0 <= ny < n:
                # 更新できるマスは更新
                if distance[nx][ny] > dis:
                    distance[nx][ny] = dis
                    d.append((nx, ny, dis + check[nx][ny]))

    return ans



distance = [[min(i, j, n - i - 1, n - j - 1) for i in range(n)] for j in range(n)]
check = [[1] * n for i in range(n)]
anss=0
for i in p:
    x = (i - 1) // n
    y = (i - 1) % n
    anss+=bfs(x, y)

print(anss)

Submission status: Time Limit Exceeded

Solution code:
from _collections import deque
N = int(input())
P = list(map(int,input().split()))
K = []
used = [[1]*N for _ in range(N)]

for i in range(N*N):
    K.append([(P[i]-1)//N, (P[i]-1) % N])

C = [[0]*N for _ in range(N)]
for i in range(N):
    for j in range(N):
        C[i][j] = min([i, N-i-1, j, N-j-1])

ans = 0
move = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i in range(N*N):
    a,b = K[i]
    used[a][b] = 0
    ans += C[a][b]
    q = deque([[a, b]])
    while(len(q)>0):
        s,t = q.popleft()
        for j,k in move:
            after_s = s+j
            after_t = t+k
            if 0 <= after_s <= N-1:
                if 0 <= after_t <= N-1:
                    c = C[s][t]
                    if used[s][t] == 1:
                        c += 1
                    if c < C[after_s][after_t]:
                        C[after_s][after_t] = c
                        q.append([after_s, after_t])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    from collections import deque
    n = int(input())
    p = list(map(int, input().split()))

    # 迷路　BFS
    def bfs(sx, sy):
        d = deque()
        d.append((sx, sy, distance[sx][sy]))
        ans = distance[sx][sy]
        v = distance[sx][sy]
        check[sx][sy] = 0

        while len(d):
            x, y, dis = d.popleft()
            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

                if 0 <= nx < n and 0 <= ny < n:
                    # 更新できるマスは更新
                    if distance[nx][ny] > dis:
                        distance[nx][ny] = dis
                        d.append((nx, ny, dis + check[nx][ny]))

        return ans

    distance = [[0 for i in range(n)] for j in range(n)]
    for i in range(n):
        for j in range(n):
            distance[i][j] += min(i, j, n - i - 1, n - j - 1)
    check = [[1] * n for i in range(n)]

    anss = 0
    for i in p:
        x = (i - 1) // n
        y = (i - 1) % n
        anss += bfs(x, y)

    print(anss)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

# 迷路　BFS
def bfs(sx,sy):
    d = deque()
    d.append((sx, sy,distance[sx][sy]))
    ans=distance[sx][sy]
    v=distance[sx][sy]
    check[sx][sy]=0

    while len(d):
        x, y,dis = d.popleft()
        for i in range(0, 4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

            if 0 <= nx < n and 0 <= ny < n:
                # 更新できるマスは更新
                if distance[nx][ny]>dis:
                    distance[nx][ny]=dis
                    d.append((nx, ny,dis+check[nx][ny]))

    return ans

distance = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
    for j in range(n):
        distance[i][j]+=min(i,j,n-i-1,n-j-1)
check = [[1]*n for i in range(n)]


anss=0
for i in p:
    x=(i-1)//n
    y=(i-1)%n
    anss+=bfs(x,y)

print(anss)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def main():
  N = int(input())
  P = list(map(int, input().split()))
  grid = [[1]*N for _ in range(N)]
  c = [[min(min(i, N-1-i), min(j, N-1-j)) for i in range(N+1)] for j in range(N+1)]
  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
        cnow = c[nowy][nowx]
        gnow = grid[nowy][nowx]
        if c[nxy][nxx] > cnow + gnow:
          c[nxy][nxx] = cnow + gnow
          stack.append((nxy, nxx))

  print(ans)

if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    # import sys
    # input = sys.stdin.readline

    N = int(input())
    *p, = (int(x) - 1 for x in input().split())

    H = [[-1] * (N + 1) for _ in range(N + 1)]  # 離席コスト,J字にコスト-1の区画を設ける
    for r in range((N + 1) // 2 + 1):
        dr = min(r, N - 1 - r)
        for c in range((N + 1) // 2 + 1):
            dc = min(c, N - 1 - c)
            H[r][c] = H[N - 1 - r][c] = H[N - 1 - r][N - 1 - c] = H[r][N - 1 - c] = min(dr, dc)
    S = [[1] * N for _ in range(N)]  # 着席

    ans = 0
    for pi in p:
        pi_r, pi_c = divmod(pi, N)

        hpi = H[pi_r][pi_c]  # piの離席コスト
        ans += hpi  # piの離席コストを加算
        S[pi_r][pi_c] = 0  # piを空席にする

        # BFSで離席コストを更新
        dq = deque()
        dq.append((pi_r, pi_c, hpi))
        while dq:
            r, c, h = dq.popleft()
            for nr, nc in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):
                if H[nr][nc] > h:
                    H[nr][nc] = h
                    dq.append((nr, nc, h + S[nr][nc]))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    import sys
    input = sys.stdin.readline

    N = int(input())
    *p, = (int(x) - 1 for x in input().split())

    H = [[-1] * (N + 1) for _ in range(N + 1)]  # 離席コスト,J字にコスト-1の区画を設ける
    for r in range((N + 1) // 2 + 1):
        dr = min(r, N - 1 - r)
        for c in range((N + 1) // 2 + 1):
            dc = min(c, N - 1 - c)
            H[r][c] = H[N - 1 - r][c] = H[N - 1 - r][N - 1 - c] = H[r][N - 1 - c] = min(dr, dc)
    S = [[1] * N for _ in range(N)]  # 着席

    ans = 0
    for pi in p:
        pi_r, pi_c = divmod(pi, N)

        hpi = H[pi_r][pi_c]  # piの離席コスト
        ans += hpi  # piの離席コストを加算
        S[pi_r][pi_c] = 0  # piを空席にする

        # BFSで離席コストを更新
        dq = deque()
        dq.append((pi_r, pi_c, hpi))
        while dq:
            r, c, h = dq.popleft()
            for nr, nc in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):
                if H[nr][nc] > h:
                    H[nr][nc] = h
                    dq.append((nr, nc, h + S[nr][nc]))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def build_cost_table(n):
    ret = [[-1] * (n + 1) for _ in range(n + 1)]  # J字にコスト-1の区画を設ける
    for r in range(n):
        dr = min(r, n - 1 - r)
        for c in range(n):
            if ~ret[r][c]: continue
            dc = min(c, n - 1 - c)
            ret[r][c] = ret[n - 1 - r][c] = ret[n - 1 - r][n - 1 - c] = ret[r][n - 1 - c] = min(dr, dc)
    return ret


def main():
    from collections import deque

    N = int(input())
    *p, = (int(x) - 1 for x in input().split())

    H = build_cost_table(N)  # 離席コスト
    S = [[1] * N for _ in range(N)]  # 着席

    ans = 0
    for pi in p:
        pi_r, pi_c = divmod(pi, N)

        hpi = H[pi_r][pi_c]  # piの離席コスト
        ans += hpi  # piの離席コストを加算
        S[pi_r][pi_c] = 0  # piを空席にする

        # BFSで離席コストを更新
        dq = deque()
        dq.append((pi_r, pi_c, hpi))
        while dq:
            r, c, h = dq.popleft()
            for nr, nc in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):
                if H[nr][nc] > h:
                    H[nr][nc] = h
                    dq.append((nr, nc, h + S[nr][nc]))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def build_cost_table(n):
    ret = [[-1] * (n + 1) for _ in range(n + 1)]  # J字にコスト-1の区画を設ける
    for r in range(n):
        dr = min(r, n - 1 - r)
        for c in range(n):
            if ~ret[r][c]: continue
            dc = min(c, n - 1 - c)
            ret[r][c] = ret[n - 1 - r][c] = ret[n - 1 - r][n - 1 - c] = ret[r][n - 1 - c] = min(dr, dc)
    return ret


def main():
    from collections import deque

    def next_coods(r, c):
        # if r != 0:
        yield r - 1, c
        # if c != 0:
        yield r, c - 1
        # if r != N - 1:
        yield r + 1, c
        # if c != N - 1:
        yield r, c + 1

    N = int(input())
    *p, = (int(x) - 1 for x in input().split())

    H = build_cost_table(N)  # 離席コスト
    S = [[1] * N for _ in range(N)]  # 着席

    ans = 0
    for pi in p:
        pi_r, pi_c = divmod(pi, N)

        hpi = H[pi_r][pi_c]  # piの離席コスト
        ans += hpi  # piの離席コストを加算
        S[pi_r][pi_c] = 0  # piを空席にする

        # BFSで離席コストを更新
        dq = deque()
        dq.append((pi_r, pi_c, hpi))
        while dq:
            r, c, h = dq.popleft()
            for nr, nc in next_coods(r, c):
                if H[nr][nc] > h:
                    H[nr][nc] = h
                    dq.append((nr, nc, h + S[nr][nc]))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def build_cost_table(n):
    ret = [[-1] * n for _ in range(n)]
    for r in range(n):
        dr = min(r, n - 1 - r)
        for c in range(n):
            if ~ret[r][c]: continue
            dc = min(c, n - 1 - c)
            ret[r][c] = ret[n - 1 - r][c] = ret[n - 1 - r][n - 1 - c] = ret[r][n - 1 - c] = min(dr, dc)
    return ret


def main():
    from collections import deque

    def next_coods(r, c):
        if r != 0:
            yield r - 1, c
        if c != 0:
            yield r, c - 1
        if r != N - 1:
            yield r + 1, c
        if c != N - 1:
            yield r, c + 1

    N = int(input())
    *p, = (int(x) - 1 for x in input().split())

    H = build_cost_table(N)  # 離席コスト
    S = [[1] * N for _ in range(N)]  # 着席

    ans = 0
    for pi in p:
        pi_r, pi_c = divmod(pi, N)

        hpi = H[pi_r][pi_c]  # piの離席コスト
        ans += hpi  # piの離席コストを加算
        S[pi_r][pi_c] = 0  # piを空席にする

        # BFSで離席コストを更新
        dq = deque()
        dq.append((pi_r, pi_c, hpi))
        while dq:
            r, c, h = dq.popleft()
            for nr, nc in next_coods(r, c):
                if H[nr][nc] > h:
                    H[nr][nc] = h
                    dq.append((nr, nc, h + S[nr][nc]))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline

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

geta = N+2
G = [0]*(geta*geta)

for v in range(-1-(-N//2), -1, -1):
    l = v+1
    r = N-v
    for i in range(geta):
        G[i*geta+l] = v
        G[i*geta+r] = v
        G[l*geta+i] = v
        G[r*geta+i] = v

for i in range(geta):
    G[i*geta] = -1
    G[i*geta + geta-1] = -1
    G[i] = -1
    G[geta*(geta-1)+i] = -1

Pn = []

for p in P:
    a, b = divmod(p-1, N)
    Pn.append((1+a)*geta+1+b)

DIREC = [1, -1, geta, -geta]
ans = 0
used = [False]*(geta*geta)
for p in Pn:
    ans += G[p]
    res = G[p]
    for d in DIREC:
        res = min(res, G[p+d])
    if G[p] != res:
        G[p] = res
        Q = [p]
        while Q:
            vn = Q.pop()
            for d in DIREC:
                vf = vn + d
                if not used[vf]:
                    if G[vf] > G[vn] + 1:
                        G[vf] = G[vn] + 1
                        Q.append(vf)
                else:
                    if G[vf] > G[vn]:
                        G[vf] = G[vn]
                        Q.append(vf)
                    
    used[p] = True
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def build_cost_table(n):
    ret = [[-1] * n for _ in range(n)]
    for r in range(n):
        dr = min(r, n - 1 - r)
        for c in range(n):
            if ~ret[r][c]: continue
            dc = min(c, n - 1 - c)
            ret[r][c] = ret[n - 1 - r][c] = ret[n - 1 - r][n - 1 - c] = ret[r][n - 1 - c] = min(dr, dc)
    return ret


def main():
    from collections import deque

    def next_coods(r, c):
        if r > 0:
            yield r - 1, c
        if c > 0:
            yield r, c - 1
        if r < N - 1:
            yield r + 1, c
        if c < N - 1:
            yield r, c + 1

    N = int(input())
    *p, = (int(x) - 1 for x in input().split())

    H = build_cost_table(N)  # 離席コスト
    S = [[1] * N for _ in range(N)]  # 着席

    ans = 0
    for pi in p:
        pi_r, pi_c = divmod(pi, N)

        hpi = H[pi_r][pi_c]  # piの離席コスト
        ans += hpi  # piの離席コストを加算
        S[pi_r][pi_c] = 0  # piを空席にする

        # BFSで離席コストを更新
        dq = deque()
        dq.append((pi_r, pi_c, hpi))
        while dq:
            r, c, h = dq.popleft()
            for nr, nc in next_coods(r, c):
                if H[nr][nc] > h:
                    H[nr][nc] = h
                    dq.append((nr, nc, h + S[nr][nc]))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline

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

geta = N+2
G = [0]*(geta*geta)

for v in range(-1-(-N//2), -1, -1):
    l = v+1
    r = N-v
    for i in range(geta):
        G[i*geta+l] = v
        G[i*geta+r] = v
        G[l*geta+i] = v
        G[r*geta+i] = v

for i in range(geta):
    G[i*geta] = -1
    G[i*geta + geta-1] = -1
    G[i] = -1
    G[geta*(geta-1)+i] = -1

Pn = []

for p in P:
    a, b = divmod(p-1, N)
    Pn.append((1+a)*geta+1+b)

DIREC = [1, -1, geta, -geta]
ans = 0
used = [False]*(geta*geta)
for p in Pn:
    ans += G[p]
    res = G[p]
    for d in DIREC:
        res = min(res, G[p+d])
    if G[p] != res:
        G[p] = res
        Q = deque([p])
        while Q:
            vn = Q.pop()
            for d in DIREC:
                vf = vn + d
                if not used[vf]:
                    if G[vf] > G[vn] + 1:
                        G[vf] = G[vn] + 1
                        Q.appendleft(vf)
                else:
                    if G[vf] > G[vn]:
                        G[vf] = G[vn]
                        Q.appendleft(vf)
                    
    used[p] = True
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline

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

geta = N+2
G = [0]*(geta*geta)

for v in range(-1-(-N//2), -1, -1):
    l = v+1
    r = N-v
    for i in range(geta):
        G[i*geta+l] = v
        G[i*geta+r] = v
        G[l*geta+i] = v
        G[r*geta+i] = v

for i in range(geta):
    G[i*geta] = -1
    G[i*geta + geta-1] = -1
    G[i] = -1
    G[geta*(geta-1)+i] = -1

Pn = []

for p in P:
    a, b = divmod(p-1, N)
    Pn.append((1+a)*geta+1+b)

DIREC = [1, -1, geta, -geta]
ans = 0
used = set()
for p in Pn:
    ans += G[p]
    Q = deque([p])
    res = G[p]
    for d in DIREC:
        res = min(res, G[p+d])
    if G[p] != res:
        G[p] = res
        while Q:
            vn = Q.pop()
            for d in DIREC:
                vf = vn + d
                if vf not in used and G[vf] > G[vn] + 1:
                    G[vf] = G[vn] + 1
                    Q.appendleft(vf)
                elif vf in used and G[vf] > G[vn]:
                    G[vf] = G[vn]
                    Q.appendleft(vf)
                    
    used.add(p)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding=utf-8
# Author: lee215
get = lambda: int(raw_input().strip())
getl = lambda: raw_input().strip()
gets = lambda: map(int, raw_input().strip().split())
getss = lambda n: [gets() for _ in xrange(n)]

raw_input = input
xrange = range

n = get()
A = gets()


dp = [[n] * n for i in xrange(n)]
for i in xrange(n):
    for j in xrange(n):
        dp[i][j] = min(i, j, n - 1 - i, n - 1 - j)
occ = [[1] * n for i in xrange(n)]

res = 0
for a in A:
    a -= 1
    i, j = a // n, a % n
    res += dp[i][j]
    occ[i][j] = 0
    queue = [[i, j, dp[i][j]]]
    while queue:
        x, y, v = queue.pop()
        v += occ[x][y]
        for i, j in [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]]:
            if not (0 <= i < n and 0 <= j < n): continue
            if dp[i][j] <= v: continue
            dp[i][j] = v
            queue.append((i, j, v))
print(res)

Submission status: Time Limit Exceeded

Solution code:
# coding=utf-8
# Author: lee215
get = lambda: int(raw_input().strip())
getl = lambda: raw_input().strip()
gets = lambda: map(int, raw_input().strip().split())
getss = lambda n: [gets() for _ in xrange(n)]

raw_input = input
xrange = range

n = get()
A = gets()


dp = [[n] * n for i in xrange(n)]
for i in xrange(n):
    for j in xrange(n):
        dp[i][j] = min(i, j, n - 1 - i, n - 1 - j)
occ = [[1] * n for i in xrange(n)]

res = 0
for a in A:
    a -= 1
    i, j = a // n, a % n
    res += dp[i][j]
    occ[i][j] = 0
    bfs = [[i, j, dp[i][j]]]

    for x, y, v in bfs:
        v += occ[x][y]
        for i, j in [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]]:
            if not (0 <= i < n and 0 <= j < n): continue
            if dp[i][j] <= v: continue
            dp[i][j] = v
            bfs.append((i, j, v))
print(res)

Submission status: Time Limit Exceeded

Solution code:
# coding=utf-8
# Author: lee215
# Date:

import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline

get = lambda: int(raw_input().strip())
getl = lambda: raw_input().strip()
gets = lambda: map(int, raw_input().strip().split())
getss = lambda n: [gets() for _ in xrange(n)]

raw_input = input
xrange = range

n = get()
A = gets()


dp = [[n] * n for i in xrange(n)]
for i in xrange(n):
    for j in xrange(n):
        dp[i][j] = min(i, j, n - 1 - i, n - 1 - j)
occ = [[1] * n for i in xrange(n)]


def dfs(i, j, x, force=False):
    if not force:
        if not (0 <= i < n and 0 <= j < n): return
        if dp[i][j] <= x: return
    dp[i][j] = x
    x += occ[i][j]
    dfs(i + 1, j, x)
    dfs(i - 1, j, x)
    dfs(i, j + 1, x)
    dfs(i, j - 1, x)

res = 0
for a in A:
    a -= 1
    i, j = a // n, a % n
    res += dp[i][j]
    occ[i][j] = 0
    dfs(i, j, dp[i][j], True)
print(res)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    N=I()
    P=LI()
    d=[[1]*N for _ in range(N)]
    
    def ij_to(i,j):
        return i*N+j
    
    def num_to(X):
        return (X//N,X%N)
    
    dx=[0,0,1,-1]
    dy=[1,-1,0,0]
    
    from collections import deque
    ans=0
    
    for pi in range(N*N):
        t=P[pi]-1
        i,j=num_to(t)
        d[i][j]=0
        dq=deque()#コストと位置
        dq.append((0,i,j))
        use=[[0]*N for _ in range(N)]
        use[i][j]=1
        while True:
            cost,ii,jj=dq.pop()
            #print(pi,cost,ii,jj)
            if ii==0 or ii==(N-1) or jj==0 or jj==(N-1):
                ans+=cost
                break
            
            for k in range(4):
                ni=ii+dx[k]
                nj=jj+dy[k]
                if use[ni][nj]==0:
                    use[ni][nj]=1
                    if d[ni][nj]==1:
                        dq.appendleft((cost+1,ni,nj))
                    else:
                        dq.append((cost,ni,nj))
                        
    print(ans)
                
        
        
        

main()

Submission status: Time Limit Exceeded

Solution code:
# coding=utf-8
# Author: lee215
# Date:

import sys
sys.setrecursionlimit(10**6)

get = lambda: int(raw_input().strip())
getl = lambda: raw_input().strip()
gets = lambda: map(int, raw_input().strip().split())
getss = lambda n: [gets() for _ in xrange(n)]

raw_input = input
xrange = range

n = get()
A = gets()


dp = [[n] * n for i in xrange(n)]
for i in xrange(n):
    for j in xrange(n):
        dp[i][j] = min(i, j, n - 1 - i, n - 1 - j)
occ = [[1] * n for i in xrange(n)]


def dfs(i, j, x, force=False):
    if not force:
        if not (0 <= i < n and 0 <= j < n): return
        if dp[i][j] <= x: return
    dp[i][j] = x
    x += occ[i][j]
    dfs(i + 1, j, x)
    dfs(i - 1, j, x)
    dfs(i, j + 1, x)
    dfs(i, j - 1, x)

res = 0
for a in A:
    a -= 1
    i, j = a // n, a % n
    res += dp[i][j]
    occ[i][j] = 0
    dfs(i, j, dp[i][j], True)
print(res)

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 = deque([i - 1])
    while q:
        l = q.pop()
        a, b = l // n, l % n
        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 * n + bi)]

print(ans)