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:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
import numpy as np
#from copy import deepcopy
#from collections import deque
import numba

def run():
    N = int(input())
    P = np.array((list(map(int, sysread().split()))))
    P -= 1

    #@numba.njit("void(i8,i8[:])")
    def proc(N, P):
        ans = 0
        Removed = np.zeros((500, 500), dtype=np.int8)
        Mat = np.zeros((500, 500), dtype=np.int16)
        Dy, Dx = [1, 0, -1, 0], [0, 1, 0, -1]

        for y in range(N):
            for x in range(N):
                Mat[y, x] = min(y, N - 1 - y, x, N - 1 - x)
        # print(Mat)
        for i in range(N * N):
            p = P[i]
            y, x = divmod(p, N)
            ans += Mat[y, x]
            Removed[y, x] = 1
            st = [(y, x)]
            while st:
                vy, vx = st.pop()
                vr = Removed[vy, vx]
                val = Mat[vy, vx]
                # for dy, dx in zip(Dy, Dx):
                for j in range(4):
                    uy, ux = vy + Dy[j], vx + Dx[j]
                    if not (0 <= uy < N and 0 <= ux < N):
                        continue
                    ur = Removed[uy, ux]
                    if vr:
                        if Mat[uy, ux] >= val + 1:
                            Mat[uy, ux] = val
                            st.append((uy, ux))
                    else:
                        if Mat[uy, ux] >= val + 2:
                            Mat[uy, ux] = val + 1
                            st.append((uy, ux))
        # for m in Mat:
        #     print(m)
        print(ans)

    proc(N, P)


if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
import numpy as np


def main(N, P):
    lista = [1, -1, N, -N]
    d = np.zeros((N, N), dtype=np.int32)
    d = d.ravel()
    sit = np.ones_like(d)
    stack = np.empty_like(d)
    count = 0
    for i in range(N*N):
        d[i] = min(i % N, (N-1-i) % N, i//N, N-1-i//N)
    for player in P:
        sit[player-1] = 0
        count += d[player-1]
        stack[0] = player
        num = 0
        while num >= 0:
            p = stack[num]
            num -= 1
            a = d[p-1]+sit[p-1]
            for i in lista:
                if p+i < 1 or p + i > N*N:
                    continue
                if d[p+i-1] > a:
                    d[p+i-1] = a
                    num += 1
                    stack[num] = p+i
    print(count)


def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i8,i8[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    #from my_module import main
    N = int(input())
    P = np.array(input().split(), np.int32)
    #N = 500
    #P = [(i+4030) % N*N for i in range(N*N)]
    main(N, P)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.buffer.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
import numpy as np
#from copy import deepcopy
from collections import deque

def run():
    N = int(input())
    P = list(map(int, sysread().split()))
    seats = np.array([[0] * N for _ in range(N)])
    seen = [[0] * N for _ in range(N)]# there is a person : 1
    left, right, up, down = 0, N-1, 0, N-1
    dist = 0
    while True:
        seats[up,left:right+1] = dist
        seats[down,left:right + 1] = dist
        seats[up:down+1, left] = dist
        seats[up:down+1, right] = dist
        left += 1
        right -= 1
        up += 1
        down -= 1
        dist+= 1
        if left > right or up > down:
            break

    ret = 0
    ###
    for i in range(N**2):
        #print(seats)
        way = {}
        cur_i, cur_j = (P[i] - 1) // N, (P[i] - 1) % N
        ret += seats[cur_i, cur_j]
        seen[cur_i][cur_j] = 1
        del_val = seats[cur_i, cur_j]
        stack = deque([(del_val, (cur_i, cur_j))])

        while stack:
            del_val, (cur_i,cur_j) = stack.popleft()
            way[cur_i * N + cur_j] = 0
            for i,j in ((1,0),(0,1),(-1,0),(0,-1)):
                n_i = cur_i + i
                n_j = cur_j + j
                if 0 <= n_i <= N - 1 and 0 <= n_j <= N - 1 and n_i * N + n_j not in way.keys():
                    if del_val < seats[n_i, n_j]:
                        seats[n_i, n_j] = del_val
                        stack.append((del_val + 1, (n_i, n_j)))
                    elif seen[n_i][n_j]:
                        stack.append((del_val, (n_i, n_j)))

    print(ret)


if __name__ == "__main__":
    run()
    from time import time
    a = time()
    tmp = [0] * 25000
    for i in range(25000):
        t = tmp[:]
    b = time()
    print(b-a, 'sec')

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
import numpy as np


def cc_export():
    @njit('(i4, i4[:, :], b1[:], i4[:], i4)')
    def update(n, que, there, cost, pos):
        l = 0
        i = 0

        que[l, 0] = pos
        que[l, 1] = cost[pos] - 1
        # que[l] = pos, cost[pos] - 1
        l += 1

        while i < l:
            pos, dist = que[i]
            i += 1

            if cost[pos] <= dist:
                continue

            y, x = divmod(pos, n)
            cost[pos] = dist

            if y >= 1:
                pp = (y - 1) * n + x
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if y <= n - 2:
                pp = (y + 1) * n + x
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if x >= 1:
                pp = y * n + (x - 1)
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if x <= n - 2:
                pp = y * n + (x + 1)
                cc = int(there[pp])
                que[l] = (pp, dist + cc)
                l += 1

    @njit('(i4, i4[:])')
    def main(n, p):
        que = np.zeros((4 * n * n, 2), dtype=np.int32)
        there = np.full(n * n, True)
        cost = np.array([
            min(i, n - i - 1, j, n - j - 1) for j in range(n) for i in range(n)
        ],
                        dtype=np.int32)

        ans = 0
        for pos in p:
            ans += cost[pos]
            there[pos] = False
            update(n, que, there, cost, pos)
        return ans

    from numba.pycc import CC
    cc = CC('solution')
    cc.export('update', '(i4, i4[:, :], b1[:], i4[:], i4)')(update)
    cc.export('main', '(i4, i4[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        sys.exit(0)

    from solution import update, main
    n = int(input())
    p = np.array(list(map(lambda x: int(x) - 1,
                          input().split())),
                 dtype=np.int32)
    print(main(n, p))

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
import numpy as np


def cc_export():
    @njit('(i8, i8[:, :], b1[:], i8[:], i8)')
    def update(n, que, there, cost, pos):
        l = 0
        i = 0

        que[l, 0] = pos
        que[l, 1] = cost[pos] - 1
        # que[l] = pos, cost[pos] - 1
        l += 1

        while i < l:
            pos, dist = que[i]
            i += 1

            if cost[pos] <= dist:
                continue

            y, x = pos // n, pos % n
            cost[pos] = dist

            if y >= 1:
                pp = (y - 1) * n + x
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if y <= n - 2:
                pp = (y + 1) * n + x
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if x >= 1:
                pp = y * n + (x - 1)
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if x <= n - 2:
                pp = y * n + (x + 1)
                cc = int(there[pp])
                que[l] = (pp, dist + cc)
                l += 1

    @njit('(i8, i8[:])')
    def main(n, p):
        que = np.zeros((4 * n * n, 2), dtype=np.int64)
        there = np.full(n * n, True)
        cost = np.array([
            min(i, n - i - 1, j, n - j - 1) for j in range(n) for i in range(n)
        ],
                        dtype=np.int64)

        ans = 0
        for pos in p:
            ans += cost[pos]
            there[pos] = False
            update(n, que, there, cost, pos)
        return ans

    from numba.pycc import CC
    cc = CC('solution')
    cc.export('update', '(i8, i8[:, :], b1[:], i8[:], i8)')(update)
    cc.export('main', '(i8, i8[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        sys.exit(0)

    from solution import update, main
    n = int(input())
    p = np.array(list(map(lambda x: int(x) - 1,
                          input().split())),
                 dtype=np.int64)
    print(main(n, p))

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
import numpy as np


def cc_export():
    @njit('(i8, i8[:, :], b1[:], i8[:], i8)')
    def update(n, que, there, cost, pos):
        l = 0
        i = 0

        que[l, 0] = pos
        que[l, 1] = cost[pos] - 1
        # que[l] = pos, cost[pos] - 1
        l += 1

        while i < l:
            pos, dist = que[i]
            i += 1

            if cost[pos] <= dist:
                continue

            y, x = pos // n, pos % n
            cost[pos] = dist

            if y >= 1:
                pp = (y - 1) * n + x
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if y <= n - 2:
                pp = (y + 1) * n + x
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if x >= 1:
                pp = y * n + (x - 1)
                cc = int(there[pp])
                #que.append((pp, dist + cc))
                que[l] = (pp, dist + cc)
                l += 1
            if x <= n - 2:
                pp = y * n + (x + 1)
                cc = int(there[pp])
                que[l] = (pp, dist + cc)
                l += 1

    @njit('(i8, i8[:])')
    def main(n, p):
        que = np.zeros((10 * n * n, 2), dtype=np.int64)
        there = np.full(n * n, True)
        cost = np.array([
            min(i, n - i - 1, j, n - j - 1) for j in range(n) for i in range(n)
        ],
                        dtype=np.int64)

        ans = 0
        for pos in p:
            ans += cost[pos]
            there[pos] = False
            update(n, que, there, cost, pos)
        return ans

    from numba.pycc import CC
    cc = CC('solution')
    cc.export('update', '(i8, i8[:, :], b1[:], i8[:], i8)')(update)
    cc.export('main', '(i8, i8[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        sys.exit(0)

    from solution import update, main
    n = int(input())
    p = np.array(list(map(lambda x: int(x) - 1,
                          input().split())),
                 dtype=np.int64)
    print(main(n, p))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
P = list(map(int, input().split()))
INF = 10**18
MAP = ['#']*(n**2)
DIRC = [(-1, 0), (0, 1), (1, 0), (0, -1)]


def bfs(init_v):
    next_v = deque([init_v])
    dist = [INF]*(n**2)
    dist[to_v(*init_v)] = 0
    MAP[to_v(*init_v)] = '.'
    mincost = INF
    quit = 0
    while next_v:
        if quit:
            break
        i, j = next_v.popleft()
        for di, dj in DIRC:
            x, y = i+di, j+dj
            if x < 0 or y < 0 or n <= x or n <= y:
                if dist[to_v(i, j)] < mincost:
                    mincost = dist[to_v(i, j)]
                    if mincost == 0:
                        quit = 1
                        break
                continue
            cost = 0 if MAP[to_v(x, y)] == '.'else 1
            if dist[to_v(x, y)] <= dist[to_v(i, j)]+cost:
                continue
            dist[to_v(x, y)] = dist[to_v(i, j)]+cost
            next_v.append((x, y))
    return dist, mincost


def to_idx(p):
    i, j = divmod(p-1, n)
    return i, j


def to_v(i, j):
    return i*n+j


ans = 0
# よく考えたら、これO(N**4)だった
for p in P:
    dist, mincost = bfs(to_idx(p))
    ans += mincost
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
P = list(map(int, input().split()))
INF = 10**18
MAP = ['#']*(n**2)
DIRC = [(-1, 0), (0, 1), (1, 0), (0, -1)]


def bfs(init_v):
    next_v = deque([init_v])
    dist = [INF]*(n**2)
    dist[to_v(*init_v)] = 0
    MAP[to_v(*init_v)] = '.'
    mincost = INF
    while next_v:
        i, j = next_v.popleft()
        for di, dj in DIRC:
            x, y = i+di, j+dj
            if x < 0 or y < 0 or n <= x or n <= y:
                if dist[to_v(i, j)] < mincost:
                    mincost = dist[to_v(i, j)]
                continue
            cost = 0 if MAP[to_v(x, y)] == '.'else 1
            if dist[to_v(x, y)] <= dist[to_v(i, j)]+cost:
                continue
            dist[to_v(x, y)] = dist[to_v(i, j)]+cost
            next_v.append((x, y))
    return dist, mincost


def to_idx(p):
    i, j = divmod(p-1, n)
    return i, j


def to_v(i, j):
    return i*n+j


ans = 0
for p in P:
    dist, mincost = bfs(to_idx(p))
    ans += mincost
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
P = list(map(int, input().split()))
MAP = [['#']*n for _ in range(n)]
INF = 10**18
DIRC = [(-1, 0), (0, 1), (1, 0), (0, -1)]


def bfs(init_v):
    next_v = deque([init_v])
    dist = [[INF]*n for _ in range(n)]
    i, j = init_v
    dist[i][j] = 0
    MAP[i][j] = '.'
    mincost = INF
    while next_v:
        i, j = next_v.popleft()
        for di, dj in DIRC:
            x, y = i+di, j+dj
            if x < 0 or y < 0 or n <= x or n <= y:
                if dist[i][j] < mincost:
                    mincost = dist[i][j]
                continue
            cost = 0 if MAP[x][y] == '.'else 1
            if dist[x][y] <= dist[i][j]+cost:
                continue
            dist[x][y] = dist[i][j]+cost
            next_v.append((x, y))
    return dist, mincost


def to_idx(p):
    i, j = divmod(p-1, n)
    return i, j


ans = 0
for p in P:
    dist, mincost = bfs(to_idx(p))
    ans += mincost
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.buffer.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
#from collections import deque
def run():
    N = int(input())
    P = list(map(int, sysread().split()))
    seats = [[1] * N for _ in range(N)]# there is a person : 1

    def heap(i):
        stack = []
        current = ((P[i] - 1) // N, (P[i] - 1) % N)
        heappush(stack, (0, current))
        seats[current[0]][current[1]] = 0
        seen = [[0] * N for _ in range(N)]
        seen[current[0]][current[1]] = 1
        while stack:
            count, (current_i, current_j) = heappop(stack)
            if current_i == 0 or current_i == N-1 or current_j == 0 or current_j == N-1:
                break
            seen[current_i][current_j] = 1
            for i,j in ((1,0),(0,1),(-1,0),(0,-1)):
                next_i = current_i + i
                next_j = current_j + j
                if 0 <= next_i <= N-1 and 0 <= next_j <= N-1 and not seen[next_i][next_j]:
                    heappush(stack, (count + seats[next_i][next_j], (next_i, next_j)))
        return count

    ret = 0
    for i in range(N**2):
        ret += heap(i)
    print(ret)


if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
import numpy as np


def main(N, P):
    lista = [1, -1, N, -N]
    d = np.zeros((N, N), dtype=np.int32)
    d = d.ravel()
    sit = np.ones_like(d)
    que = []
    count = 0
    for i in range(N*N):
        d[i] = min(i % N, (N-1-i) % N, i//N, N-1-i//N)
    for player in P:
        sit[player-1] = 0
        count += d[player-1]
        que.append(player)
        while len(que) > 0:
            p = que.pop()
            for i in lista:
                if p+i < 1 or p + i > N*N:
                    continue
                if d[p-1]+sit[p-1] < d[p+i-1]:
                    d[p+i-1] = d[p-1]+sit[p-1]
                    que.append(p+i)
    print(count)


def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i8,i8[:])')(main)
    cc.compile()


if __name__ == '__main__':
    import sys
    if sys.argv[-1] == 'ONLINE_JUDGE':
        cc_export()
        exit(0)
    #from my_module import main
    N = int(input())
    P = list(map(int, input().split()))
    main(N, P)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.buffer.read
from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
#from collections import deque
def run():
    N = int(input())
    P = list(map(int, sysread().split()))
    seats = [[1] * N for _ in range(N)]# there is a person : 1

    def heap(i):
        stack = []
        current = ((P[i] - 1) // N, (P[i] - 1) % N)
        heappush(stack, (0, current))
        seats[current[0]][current[1]] = 0
        seen = [[0] * N for _ in range(N)]
        seen[current[0]][current[1]] = 1
        while stack:
            count, (current_i, current_j) = heappop(stack)
            seen[current_i][current_j] = 1
            for i,j in ((1,0),(0,1),(-1,0),(0,-1)):
                next_i = current_i + i
                next_j = current_j + j
                if next_i < 0 or next_i > N-1 or next_j < 0 or next_j > N-1:
                    stack = []
                    break
                if not seen[next_i][next_j]:
                    heappush(stack, (count + seats[next_i][next_j],(next_i, next_j)))
        return count

    ret = 0
    for i in range(N**2):
        ret += heap(i)
    print(ret)


if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7

def dfs(src):

    directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
    stack = []
    h, w = src
    stack.append((dist[h][w], h, w))
    while stack:
        cost, h, w = stack.pop()
        for dh, dw in directions:
            h2 = h + dh
            w2 = w + dw
            if h2 < 0 or w2 < 0 or h2 >= N or w2 >= N:
                continue
            if dist[h2][w2] > cost:
                dist[h2][w2] = cost
                stack.append((cost+seated[h2][w2], h2, w2))

N = INT()
P = [p-1 for p in LIST()]

dist = list2d(N, N, 0)
for i in range(N):
    for j in range(N):
        dist[i][j] = min(i, N-i-1, j, N-j-1)

ans = 0
seated = list2d(N, N, 1)
for p in P:
    h, w = p//N, p%N
    ans += dist[h][w]
    dfs((h, w))
    seated[h][w] = 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def to_pos(y, x):
    return y * n + x


def to_coord(pos):
    return pos // n, pos % n


def update(pos):
    que = deque()
    que.append((pos, cost[pos] - 1))
    while que:
        pos, dist = que.popleft()
        if cost[pos] <= dist:
            continue

        y, x = to_coord(pos)
        cost[pos] = dist

        if y >= 1:
            pp = to_pos(y - 1, x)
            cc = int(there[pp])
            que.append((pp, dist + cc))
        if y <= n - 2:
            pp = to_pos(y + 1, x)
            cc = int(there[pp])
            que.append((pp, dist + cc))
        if x >= 1:
            pp = to_pos(y, x - 1)
            cc = int(there[pp])
            que.append((pp, dist + cc))
        if x <= n - 2:
            pp = to_pos(y, x + 1)
            cc = int(there[pp])
            que.append((pp, dist + cc))


n = int(input())
p = map(lambda x: int(x) - 1, input().split())

there = [True] * (n * n)
cost = [min(i, n - i - 1, j, n - j - 1) for j in range(n) for i in range(n)]

ans = 0
for pos in p:
    ans += cost[pos]
    there[pos] = False
    update(pos)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys,queue,math,copy,itertools,bisect,collections
from heapq import *

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**3
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    P = LI()

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

    ans = 0
    for a in P:
        i = (a-1) % N
        j = (a-1) // N
        ans += path[i][j]

        seat[i][j] = 0

        q = collections.deque()
        q.append((i,j,path[i][j]))
        while q:
            x,y,z = q.popleft()
            if path[x][y] < z: continue
            z += seat[x][y]
            for dx,dy in ((0,1),(1,0),(0,-1),(-1,0)):
                if 0 <= x+dx < N and 0 <= y+dy < N:
                    if path[x+dx][y+dy] > z:
                        path[x+dx][y+dy] = z
                        q.append((x+dx,y+dy,z))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys,queue,math,copy,itertools,bisect,collections
from heapq import *

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**3
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N = NI()
    P = LI()

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

    ans = 0
    for a in P:
        i = (a-1) % N
        j = (a-1) // N
        ans += path[i][j]

        seat[i][j] = 0

        q = collections.deque()
        q.append((i,j,path[i][j]))
        while q:
            x,y,z = q.popleft()
            z += seat[x][y]
            for dx,dy in ((0,1),(1,0),(0,-1),(-1,0)):
                if 0 <= x+dx < N and 0 <= y+dy < N:
                    if path[x+dx][y+dy] > z:
                        path[x+dx][y+dy] = z
                        q.append((x+dx,y+dy,z))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
P = list(map(lambda x:int(x)-1,input().split()))

costs = [0]*(N*N)
for i in range(N):
    for j in range(N):
        costs[i*N+j] = min(i,j,N-1-i,N-1-j)
exist = [1]*(N*N)

from collections import deque
dxs = [0,1,0,-1]
dys = [1,0,-1,0]

ans = 0
for p in P:
    ans += costs[p]
    exist[p] = 0
    q = deque([p])
    while q:
        p = q.popleft()
        y,x = divmod(p,N)
        for dx,dy in zip(dxs,dys):
            nx,ny = x+dx,y+dy
            if not 0 <= nx < N: continue
            if not 0 <= ny < N: continue
            np = ny*N + nx
            if costs[np] > costs[p] + exist[p]:
                costs[np] = costs[p] + exist[p]
                q.append(np)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
P = list(map(lambda x:int(x)-1,input().split()))

costs = [0]*(N*N)
for i in range(N):
    for j in range(N):
        costs[i*N+j] = min(i,j,N-1-i,N-1-j)
exist = [1]*(N*N)

from collections import deque
dxy = [(0,1),(1,0),(0,-1),(-1,0)]

ans = 0
for p in P:
    ans += costs[p]
    exist[p] = 0
    q = deque([p])
    while q:
        p = q.popleft()
        y,x = divmod(p,N)
        for dx,dy in dxy:
            nx,ny = x+dx,y+dy
            if not 0 <= nx < N: continue
            if not 0 <= ny < N: continue
            np = ny*N + nx
            if costs[np] > costs[p] + exist[p]:
                costs[np] = costs[p] + exist[p]
                q.append(np)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
P = list(map(lambda x:int(x)-1,input().split()))

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

from collections import deque
dxy = [(0,1),(1,0),(0,-1),(-1,0)]

ans = 0
for p in P:
    y,x = divmod(p,N)
    ans += costs[y][x]
    exist[y][x] = 0
    q = deque([(x,y)])
    while q:
        x,y = q.popleft()
        for dx,dy in dxy:
            nx,ny = x+dx,y+dy
            if not 0 <= nx < N: continue
            if not 0 <= ny < N: continue
            if costs[ny][nx] > costs[y][x] + exist[y][x]:
                costs[ny][nx] = costs[y][x] + exist[y][x]
                q.append((nx,ny))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from numba import jit
from collections import deque
import numpy as np

def main():
  N=int(input())
  S=list(map(int,input().split()))
  count=0
  P=np.ones((N*N+1))
  d=np.zeros((N*N+1))
  que=deque()
  for i in range(N*N):
    player=S[i]
    P[player]=0
    que.clear()
    que.append((player,0))
    d[player]=i+1

    while que:
      kouho,j=que.popleft()
      if kouho%N==0:
        break
      if kouho%N==1:
        break
      if kouho+N>N*N:
        break
      if kouho<N:
        break

      if d[kouho+N]<i+1:
        if P[kouho+N]==1:
          que.append((kouho+N,j+1))
          d[kouho+N]=i+1
        else:
          que.appendleft((kouho+N,j))
          d[kouho+N]=i+1

      if d[kouho-N]<i+1:
        if P[kouho-N]==1:
          que.append((kouho-N,j+1))
          d[kouho-N]=i+1
        else:
          que.appendleft((kouho-N,j))
          d[kouho-N]=i+1

      if d[kouho+1]<i+1:
        if P[kouho+1]==1:
          que.append((kouho+1,j+1))
          d[kouho+1]=i+1
        else:
          que.appendleft((kouho+1,j))
          d[kouho+1]=i+1

      if d[kouho-1]<i+1:
        if P[kouho-1]==1:
          que.append((kouho-1,j+1))
          d[kouho-1]=i+1
        else:
          que.appendleft((kouho-1,j))
          d[kouho-1]=i+1
    count+=j

  print(count)

def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main')(main)
    cc.compile()

main()