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: Wrong Answer

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()))))

    @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: Wrong Answer

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 = [[0] * N for _ in range(N)]
    up, down = 0, N-1
    dist = 0
    while True:
        for i in range(up, down+1):
            seats[up][i] = dist
            seats[down][i] = dist
            seats[i][up] = dist
            seats[i][down] = dist
        up += 1
        down -= 1
        dist += 1
        if up > down:
            break

    ret = 0
    ###
    for i in range(N**2):
        #print(seats)
        way = defaultdict(lambda :0)
        cur_i, cur_j = (P[i] - 1) // N, (P[i] - 1) % N
        ret += seats[cur_i][cur_j]

        stack = deque([(seats[cur_i][cur_j], (cur_i, cur_j))])
        seats[cur_i][cur_j] = -1
        way[cur_i * N + cur_j] = 1
        while stack:
            del_val, (cur_i,cur_j) = stack.popleft()
            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 not way[n_i * N + n_j]:
                    if del_val < seats[n_i][n_j]:
                        seats[n_i][n_j] = del_val
                        stack.append((del_val + 1, (n_i, n_j)))
                        way[n_i * N + n_j] = 1
                    elif seats[n_i][n_j] == -1:
                        stack.append((del_val, (n_i, n_j)))
                        way[n_i * N + n_j] = 1

    print(ret)


if __name__ == "__main__":
    run()

Submission status: Wrong Answer

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 = [[0] * N for _ in range(N)]
    seen = [[0] * N for _ in range(N)]# there is a person : 1
    up, down = 0, N-1
    dist = 0
    while True:
        for i in range(up, down+1):
            seats[up][i] = dist
            seats[down][i] = dist
            seats[i][up] = dist
            seats[i][down] = dist
        up += 1
        down -= 1
        dist += 1
        if up > down:
            break

    ret = 0
    ###
    for i in range(N**2):
        #print(seats)
        way = defaultdict(lambda :0)
        cur_i, cur_j = (P[i] - 1) // N, (P[i] - 1) % N
        ret += seats[cur_i][cur_j]
        seen[cur_i][cur_j] = 1
        stack = deque([(seats[cur_i][cur_j], (cur_i, cur_j))])
        way[cur_i * N + cur_j] = 1
        while stack:
            del_val, (cur_i,cur_j) = stack.popleft()
            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 not way[n_i * N + n_j]:
                    if del_val < seats[n_i][n_j] and not seen[n_i][n_j]:
                        seats[n_i][n_j] = del_val
                        stack.append((del_val + 1, (n_i, n_j)))
                        way[n_i * N + n_j] = 1
                    elif seen[n_i][n_j]:
                        stack.append((del_val, (n_i, n_j)))
                        way[n_i * N + n_j] = 1

    print(ret)


if __name__ == "__main__":
    run()

Submission status: Wrong Answer

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 = [[0] * N for _ in range(N)]
    seen = [[0] * N for _ in range(N)]# there is a person : 1
    up, down = 0, N-1
    dist = 0
    while True:
        for i in range(up, down+1):
            seats[up][i] = dist
            seats[down][i] = dist
            seats[i][up] = dist
            seats[i][down] = dist
        up += 1
        down -= 1
        dist += 1
        if up > down:
            break

    ret = 0
    ###
    for i in range(N**2):
        #print(seats)
        way = defaultdict(lambda :0)
        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))])
        way[cur_i * N + cur_j] = 1
        while stack:
            del_val, (cur_i,cur_j) = stack.popleft()
            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 not way[n_i * N + n_j]:
                    if del_val < seats[n_i][n_j]:
                        seats[n_i][n_j] = del_val
                        stack.append((del_val + 1, (n_i, n_j)))
                        way[n_i * N + n_j] = 1
                    elif seen[n_i][n_j]:
                        stack.append((del_val, (n_i, n_j)))
                        way[n_i * N + n_j] = 1

    print(ret)


if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
Ps = list(map(lambda x: int(x)-1, input().split()))
cost = [min(min(i, n-1-i), min(j, n-1-j)) for i in range(n) for j in range(n)]
INF = 10**18
DIRC = [(-1, 0), (0, 1), (1, 0), (0, -1)]
exited = [0]*(n**2)


def bfs(init_v):
    next_v = deque([init_v])
    exited[to_v(*init_v)] = 1
    dist = [INF]*(n**2)
    dist[to_v(*init_v)] = 0
    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:
                continue
            if cost[to_v(x, y)] <= cost[to_v(i, j)]+dist[to_v(i, j)]:
                continue
            cost[to_v(x, y)] = cost[to_v(i, j)]+dist[to_v(i, j)]

            d = 0 if exited[to_v(x, y)] else 1
            if dist[to_v(x, y)] <= dist[to_v(i, j)]+d:
                continue
            dist[to_v(x, y)] = dist[to_v(i, j)]+d

            next_v.append((x, y))


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


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


ans = 0
for p in Ps:
    ans += cost[p]
    bfs(to_idx(p))

print(ans)

Submission status: Wrong Answer

Solution code:
#import numpy as np
import sys
sys.setrecursionlimit(20000)
[n], *e = [[*map(int, t.split())] for t in open(0)]
#n = 500
# np.random.seed(seed=64)
#ppp = [x + 1 for x in np.random.permutation(n * n).astype(np.int32)]
#e = [ppp]
# print(ppp)


viewers = set(range(1, n**2 + 1))
mem = {x: min((x - 1) % n, (n - x) % n, (x - 1)//n, n - 1 - (x - 1)//n)
       for x in range(1, n**2 + 1)}


def directions(x):
    tmp = []
    if x % n > 1:
        tmp.append(x - 1)
    if x % n > 0:
        tmp.append(x + 1)
    if (x - 1)//n > 0:
        tmp.append(x - n)
    if (x - 1)//n < n - 1:
        tmp.append(x + n)
    return tmp


ans = 0

for x in e[0]:
    visited = set()
    visited.add(x)

    def fill(x):
        queue = []
        for k in directions(x):
            if k not in visited:
                visited.add(k)
                if mem[k] > mem[x] + (x in viewers):
                    mem[k] = mem[x] + (x in viewers)
                    queue.append(k)
        for node in queue:
            fill(node)

    ans += mem[x]
    viewers.remove(x)
    fill(x)

print(ans)

Submission status: Wrong Answer

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 = [[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:
        for i in range(left, right+1):
            seats[up][i] = dist
            seats[down][i] = dist
        for i in range(up, down+1):
            seats[i][left] = dist
            seats[i][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 = defaultdict(lambda :0)
        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))])
        way[cur_i * N + cur_j] = 1
        while stack:
            del_val, (cur_i,cur_j) = stack.popleft()
            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 not way[n_i * N + n_j]:
                    if del_val < seats[n_i][n_j]:
                        seats[n_i][n_j] = del_val
                        stack.append((del_val + 1, (n_i, n_j)))
                        way[n_i * N + n_j] = 1
                    elif seen[n_i][n_j]:
                        stack.append((del_val, (n_i, n_j)))
                        way[n_i * N + n_j] = 1

    print(ret)


if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
#import numpy as np
import sys
sys.setrecursionlimit(20000)
[n], *e = [[*map(int, t.split())] for t in open(0)]
#n = 500
# np.random.seed(seed=64)
#ppp = [x + 1 for x in np.random.permutation(n * n).astype(np.int32)]
#e = [ppp]
# print(ppp)


viewers = set(range(1, n**2 + 1))
mem = {x: min((x - 1) % n, (n - x) % n, (x - 1)//n, n - 1 - (x - 1)//n)
       for x in range(1, n**2 + 1)}


def directions(x, val):
    tmp = []
    if x % n > 1 and mem[x - 1] > val:
        tmp.append(x - 1)
    if x % n > 0 and mem[x + 1] > val:
        tmp.append(x + 1)
    if (x - 1)//n > 0 and mem[x - n] > val:
        tmp.append(x - n)
    if (x - 1)//n < n - 1 and mem[x + n] > val:
        tmp.append(x + n)
    return tmp


ans = 0

for x in e[0]:
    visited = set()
    visited.add(x)

    def fill(x):
        queue = []
        for k in directions(x, mem[x]):
            if k not in visited:
                visited.add(k)
                if mem[k] > mem[x] + (x in viewers):
                    mem[k] = mem[x] + (x in viewers)
                    queue.append(k)
        for node in queue:
            fill(node)

    ans += mem[x]
    viewers.remove(x)
    fill(x)

print(ans)

Submission status: Wrong Answer

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
        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 = pos - n
                que[l, 0] = pp
                que[l, 1] = dist + int(there[pp])
                l += 1
            if y <= n - 2:
                pp = pos + n
                que[l, 0] = pp
                que[l, 1] = dist + int(there[pp])
                l += 1
            if x >= 1:
                pp = pos - 1
                que[l, 0] = pp
                que[l, 1] = dist + int(there[pp])
                l += 1
            if x <= n - 2:
                pp = pos - 1
                que[l, 0] = pp
                que[l, 1] = dist + int(there[pp])
                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: Wrong Answer

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 = [[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:
        for i in range(left, right+1):
            seats[up][i] = dist
            seats[down][i] = dist
        for i in range(up, down+1):
            seats[i][left] = dist
            seats[i][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 = defaultdict(lambda :0)
        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] = 1
            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 not way[n_i * N + n_j]:
                    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()

Submission status: Wrong Answer

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 = [[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:
        for i in range(left, right+1):
            seats[up][i] = dist
            seats[down][i] = dist
        for i in range(up, down+1):
            seats[i][left] = dist
            seats[i][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()

Submission status: Wrong Answer

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()

Submission status: Wrong Answer

Solution code:
#import numpy as np
import sys
sys.setrecursionlimit(20000)
[n], *e = [[*map(int, t.split())] for t in open(0)]
#n = 500
# np.random.seed(seed=64)
#ppp = [x + 1 for x in np.random.permutation(n * n).astype(np.int32)]
#e = [ppp]
# print(ppp)


viewers = set(range(1, n**2 + 1))
mem = {x: min((x - 1) % n, (n - x) % n, (x - 1)//n, n - 1 - (x - 1)//n)
       for x in range(1, n**2 + 1)}


def directions(x, val):
    tmp = []
    if x % n > 1 and mem[x - 1] > val:
        tmp.append(x - 1)
    if x % n > 0 and mem[x + 1] > val:
        tmp.append(x + 1)
    if (x - 1)//n > 0 and mem[x - n] > val:
        tmp.append(x - n)
    if (x - 1)//n < n - 1 and mem[x + n] > val:
        tmp.append(x + n)
    return tmp


ans = 0

for x in e[0]:
    visited = set()
    visited.add(x)

    def fill(x):
        queue = []
        for k in directions(x, mem[x]):
            if k not in visited:
                visited.add(k)
                mem[k] = mem[x]
                if k not in viewers:
                    queue.append(k)
        for node in queue:
            fill(node)

    ans += mem[x]
    viewers.remove(x)
    fill(x)

print(ans)

Submission status: Wrong Answer

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)
        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()
            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 not seen[n_i][n_j] and del_val < seats[n_i,n_j]:
                    seats[n_i, n_j] = del_val
                    stack.append((del_val+1, (n_i, n_j)))
    print(ret)


if __name__ == "__main__":
    run()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(20000)

[n], *e = [[*map(int, t.split())] for t in open(0)]
viewers = set(range(1, n**2 + 1))
mem = {x: min((x - 1) % n, (n - x) % n, (x - 1)//n, n - 1 - (x - 1)//n)
       for x in range(1, n**2 + 1)}


def directions(x):
    tmp = []
    if x % n > 1:
        tmp.append(x - 1)
    if x % n > 0:
        tmp.append(x + 1)
    if (x - 1)//n > 0:
        tmp.append(x - n)
    if (x - 1)//n < n - 1:
        tmp.append(x + n)
    return tmp


ans = 0

for x in e[0]:
    visited = set()
    visited.add(x)

    def fill(x):
        queue = []
        for k in directions(x):
            if k not in visited:
                visited.add(k)
                if mem[k] > mem[x]:
                    mem[k] = mem[x]
                    if k not in viewers:
                        queue.append(k)
        for node in queue:
            fill(node)

    ans += mem[x]
    viewers.remove(x)
    fill(x)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(20000)

[n], *e = [[*map(int, t.split())] for t in open(0)]
viewers = set(range(1, n**2 + 1))
mem = {x: min((x - 1) % n, (n - x) % n, (x - 1)//n, n - 1 - (x - 1)//n)
       for x in range(1, n**2 + 1)}


def directions(x):
    tmp = []
    if x % n > 1:
        tmp.append(x - 1)
    if x % n > 0:
        tmp.append(x + 1)
    if (x - 1)//n > 0:
        tmp.append(x - n)
    if (x - 1)//n < n - 1:
        tmp.append(x + n)
    return tmp


ans = 0

for x in e[0]:
    visited = set()
    visited.add(x)

    def fill(x):
        queue = []
        for k in directions(x):
            if k not in visited:
                visited.add(k)
                if mem[k] > mem[x]:
                    mem[k] = mem[x]
                    if k not in viewers:
                        queue.append(k)
        for n in queue:
            fill(k)

    ans += mem[x]
    viewers.remove(x)
    fill(x)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from numba import njit

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


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


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


@njit
def update(there, cost, pos):
    que = []
    que.append((pos, cost[pos] - 1))
    i = 0
    while i == len(que):
        pos, dist = que[i]
        i += 1

        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))


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(there, cost, pos)

print(ans)

Submission status: Wrong Answer

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
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)
        if x < N-1:
            np = p + 1
            if costs[np] > costs[p] + exist[p]:
                costs[np] = costs[p] + exist[p]
                q.append(np)
        elif x > 0:
            np = p - 1
            if costs[np] > costs[p] + exist[p]:
                costs[np] = costs[p] + exist[p]
                q.append(np)
        if y < N-1:
            np = p + N
            if costs[np] > costs[p] + exist[p]:
                costs[np] = costs[p] + exist[p]
                q.append(np)
        elif y > 0:
            np = p - N
            if costs[np] > costs[p] + exist[p]:
                costs[np] = costs[p] + exist[p]
                q.append(np)
print(ans)