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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

def main():
    N = ir()
    P = lr()
    dp = [[min(i, N-1-i)] * N for i in range(N)]
    people = [[True] * N for i in range(N)]
    for j in range(N):
        x = min(j, N-1-j)
        for i in range(N):
            dp[i][j] = min(dp[i][j], x)

    answer = 0

    def bfs(sy, sx):
        que = deque([(sy, sx, dp[sy][sx])])
        popleft = que.popleft; append = que.append
        used = set()
        while que:
            y, x, cur = popleft()
            if (y, x) in used:
                continue
            used.add((y, x))
            if cur == -1 and not people[y][x]:
                people[y][x] = True
            for dy, dx in zip([0, 1, 0, -1], [1, 0, -1, 0]):
                ny = y + dy
                nx = x + dx
                if 0 <= ny < N and 0 <= nx < N:
                    if dp[ny][nx] > cur + 1:
                        dp[ny][nx] = cur + 1
                        if not people[ny][nx]:
                            dp[ny][nx] = cur
                        if (ny, nx) not in used:
                            append((ny, nx, dp[ny][nx]))
                    elif dp[ny][nx] > cur and (not people[ny][nx]):
                        # 人がいない時
                        dp[ny][nx] = cur
                        if (ny, nx) not in used:
                            append((ny, nx, cur))

    for p in P:
        p -= 1
        i = p // N
        j = p % N
        answer += dp[i][j]
        dp[i][j] -= 1
        people[i][j] = False
        bfs(i, j)

    print(answer)
    
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
from collections import deque

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
P = lr()
dp = [[min(i, N-1-i)] * N for i in range(N)]
people = [[True] * N for i in range(N)]
for j in range(N):
    x = min(j, N-1-j)
    for i in range(N):
        dp[i][j] = min(dp[i][j], x)

answer = 0

def bfs(sy, sx):
    que = deque([(sy, sx)])
    popleft = que.popleft; append = que.append
    used = set()
    while que:
        y, x = popleft()
        if (y, x) in used:
            continue
        used.add((y, x))
        cur = dp[y][x]
        if cur == -1 and not people[y][x]:
            people[y][x] = True
        for dy, dx in zip([0, 1, 0, -1], [1, 0, -1, 0]):
            ny = y + dy
            nx = x + dx
            if 0 <= ny < N and 0 <= nx < N:
                if dp[ny][nx] > cur + 1:
                    dp[ny][nx] = cur + 1
                    if not people[ny][nx]:
                        dp[ny][nx] = cur
                    if (ny, nx) not in used:
                        append((ny, nx))
                elif dp[ny][nx] > cur and (not people[ny][nx]):
                    # 人がいない時
                    dp[ny][nx] = cur
                    if (ny, nx) not in used:
                        append((ny, nx))

for p in P:
    p -= 1
    i = p // N
    j = p % N
    answer += dp[i][j]
    dp[i][j] -= 1
    people[i][j] = False
    bfs(i, j)

print(answer)

Submission status: Time Limit Exceeded

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

def hw(p):
    h,w = divmod(p,n)
    return h,w

def toP(h,w):
    return h * n + w

fs = [[0]*n for i in range(n)]
## フロアフィールドを作る
for i in range(n):
    x = min(i,n-1-i)
    for j in range(n):
        y = min(j,n-1-j)
        fs[i][j] = min(x,y)

ans = 0
mvs = [(1,0),(-1,0),(0,1),(0,-1)]
# occupied = [[1]*n for i in range(n)]
occupied = [1] * (n**2)
for p in Ps:
    p -= 1
    h,w = hw(p) 
    ans += fs[h][w]
    occupied[p] = 0
    q = deque([])
    q.append(p)
    while len(q) > 0: #pを起点にBFS
        p_ = q.popleft()
        h, w = hw(p_)
        dist = fs[h][w]
        for dh,dw in mvs:
            if 0<=h+dh<n and 0<=w+dw<n:
                # ある位置h,wが
                # occupiedなら、隣接マス+1で到達
                # vacantなら、隣接マス+0で到達
                if dist+occupied[p_] < fs[h+dh][w+dw]:
                    q.append(toP(h+dh,w+dw))
                    fs[h+dh][w+dw] = dist + occupied[p_]                
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
buff_readline = sys.stdin.buffer.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def slv(N, P):
    P = [p-1 for p in P]
    cost = [1] * N**2
    occupy = [1] * N**2
    for i in range(N):
        for j in range(N):
            cost[i*N+j] = min(i, j, N-i-1, N-j-1)

    # print('--- init')
    # for i in range(N):
    #     print([cost[i*N+j] for j in range(N)])

    ans = 0
    for p in P:
        ans += cost[p]
        occupy[p] = 0
        i = p // N
        j = p % N
        s = [(i, j)]
        while s:
            x, y = s.pop()
            pi = x*N + y
            for i, j in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:
                if 0 <= i < N and 0 <= j < N:
                    ni = i*N + j
                    nc = cost[pi] + occupy[pi]
                    if nc < cost[ni]:
                        s.append((i, j))
                        cost[ni] = nc

    return ans


def main():
    N = read_int()
    P = read_int_n()
    print(slv(N, P))

    # N = 500
    # P = list(range(1, N**2+1))
    # random.shuffle(P)
    # print(slv(N, P))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def hw(p):
    h,w = divmod(p-1,n)
    return h,w

def toP(h,w):
    return h * n + w + 1

fs = [[0]*n for i in range(n)]
## フロアフィールドを作る
for i in range(n):
    x = min(i,n-1-i)
    for j in range(n):
        y = min(j,n-1-j)
        fs[i][j] = min(x,y)

ans = 0
mvs = [(1,0),(-1,0),(0,1),(0,-1)]
occupied = [[1]*n for i in range(n)]

for p in Ps:
    h,w = hw(p) 
    ans += fs[h][w]
    occupied[h][w] = 0
    q = deque([])
    q.append(p)
    while len(q) > 0: #pを起点にBFS
        p_ = q.popleft()
        h, w = hw(p_)
        dist = fs[h][w]
        for dh,dw in mvs:
            if 0<=h+dh<n and 0<=w+dw<n:
                # ある位置h,wが
                # occupiedなら、隣接マス+1で到達
                # vacantなら、隣接マス+0で到達
                if dist+occupied[h][w] < fs[h+dh][w+dw]:
                    q.append(toP(h+dh,w+dw))
                    fs[h+dh][w+dw] = dist + occupied[h][w]

                
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
from collections import deque

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
P = lr()
dp = [[min(i, N-1-i)] * N for i in range(N)]
people = [[True] * N for i in range(N)]
for j in range(N):
    x = min(j, N-1-j)
    for i in range(N):
        dp[i][j] = min(dp[i][j], x)

answer = 0

def bfs(sy, sx):
    que = deque([(sy, sx)])
    popleft = que.popleft; append = que.append
    while que:
        y, x = popleft()
        if (y, x) in used:
            continue
        used.add((y, x))
        cur = dp[y][x]
        if cur == -1 and not people[y][x]:
            people[y][x] = True
        for dy, dx in zip([0, 1, 0, -1], [1, 0, -1, 0]):
            ny = y + dy
            nx = x + dx
            if 0 <= ny < N and 0 <= nx < N:
                if dp[ny][nx] > cur + 1:
                    dp[ny][nx] = cur + 1
                    if not people[ny][nx]:
                        dp[ny][nx] = cur
                    append((ny, nx))
                elif dp[ny][nx] > cur and (not people[ny][nx]):
                    # 人がいない時
                    dp[ny][nx] = cur
                    append((ny, nx))

for p in P:
    p -= 1
    i = p // N
    j = p % N
    answer += dp[i][j]
    dp[i][j] -= 1
    people[i][j] = False
    used = set()

    bfs(i, j)

print(answer)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
buff_readline = sys.stdin.buffer.readline


def read_int():
    return int(buff_readline())


def read_int_n():
    return tuple(map(int, buff_readline().split()))


# from collections import deque

def slv(N, P):
    M = N+2
    cost = [0] * M**2
    occupy = [True] * M**2
    for i in range(N):
        im = i*M + M + 1
        for j in range(N):
            cost[im+j] = min(i, j, N-i-1, N-j-1)

    ds = [-1, 1, -M, M]
    ans = 0
    for p in P:
        p -= 1
        x = p // N
        y = p % N
        p = x * M + y + M + 1
        ans += cost[p]
        occupy[p] = False
        s = [p]
        while s:
            pi = s.pop()
            for d in ds:
                ni = pi + d
                nc = cost[pi] + (1 if occupy[pi] else 0)
                if nc < cost[ni]:
                    s.append(ni)
                    cost[ni] = nc
    return ans


def main():
    N = read_int()
    P = read_int_n()
    print(slv(N, P))

    # import random
    # N = 500
    # P = list(range(1, N**2+1))
    # random.shuffle(P)
    # print(slv(N, P))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
buff_readline = sys.stdin.buffer.readline


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


from collections import deque

def slv(N, P):
    M = N+2
    cost = [0] * M**2
    occupy = [True] * M**2
    for i in range(N):
        im = i*M + M + 1
        for j in range(N):
            cost[im+j] = min(i, j, N-i-1, N-j-1)

    ds = [-1, 1, -M, M]
    ans = 0
    for p in P:
        p -= 1
        x = p // N
        y = p % N
        p = x * M + y + M + 1
        ans += cost[p]
        occupy[p] = False
        s = [p]
        while s:
            pi = s.pop()
            for d in ds:
                ni = pi + d
                nc = cost[pi] + (1 if occupy[pi] else 0)
                if nc < cost[ni]:
                    s.append(ni)
                    cost[ni] = nc
    return ans


def main():
    N = read_int()
    P = read_int_n()
    print(slv(N, P))

    # import random
    # N = 500
    # P = list(range(1, N**2+1))
    # random.shuffle(P)
    # print(slv(N, P))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
buff_readline = sys.stdin.buffer.readline


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


from collections import deque

def slv(N, P):
    P = [p-1 for p in P]
    M = N+2
    cost = [0] * M**2
    occupy = [True] * M**2
    for i in range(N):
        for j in range(N):
            cost[i*M+j + M + 1] = min(i, j, N-i-1, N-j-1)

    ans = 0
    for p in P:
        x = p // N
        y = p % N
        p = x * M + y + M + 1
        ans += cost[p]
        occupy[p] = False
        s = [p]
        while s:
            pi = s.pop()
            for d in [-1, 1, -M, M]:
                ni = pi + d
                nc = cost[pi] + (1 if occupy[pi] else 0)
                if nc < cost[ni]:
                    s.append(ni)
                    cost[ni] = nc
    return ans


def main():
    N = read_int()
    P = read_int_n()
    print(slv(N, P))

    # import random
    # N = 500
    # P = list(range(1, N**2+1))
    # random.shuffle(P)
    # print(slv(N, P))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import defaultdict
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


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

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, P):
    P = [p-1 for p in P]
    cost = [1] * N**2
    occupy = [True] * N**2
    for i in range(N):
        for j in range(N):
            cost[i*N+j] = min(i, j, N-i-1, N-j-1)

    # print('--- init')
    # for i in range(N):
    #     print([cost[i*N+j] for j in range(N)])

    ans = 0
    for p in P:
        ans += cost[p]
        occupy[p] = False
        i = p // N
        j = p % N
        s = [(i, j)]
        while s:
            x, y = s.pop()
            pi = x*N + y
            for i, j in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:
                if 0 <= i < N and 0 <= j < N:
                    ni = i*N + j
                    nc = cost[pi] + (1 if occupy[pi] else 0)
                    if nc < cost[ni]:
                        s.append((i, j))
                        cost[ni] = nc

    return ans


def main():
    N = read_int()
    P = read_int_n()
    print(slv(N, P))


    # N = 500
    # P = list(range(1, N**2+1))
    # random.shuffle(P)
    # print(slv(N, P))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

d = [None] * (n**2)
for i in range(n):
    for j in range(n):
        d[i*n+j] = min(i, n-1-i, j, n-1-j)
vacant = [False] * (n**2)

ans = 0
for pos in p:
    pos -= 1
    ans += d[pos]
    vacant[pos] = True
    q = [pos]
    while q:
        pos = q.pop()
        tmp = not vacant[pos]
        for diff in (-1, 1, -n, n):
            ppos = diff+pos
            if ppos<0 or ppos>=n*n:
                continue
            if d[ppos]>d[pos]+tmp:
                d[ppos] = d[pos] + tmp
                q.append(ppos)
#         if pos+n<n*n:
#             ppos = pos + n
#             if d[ppos]>v:
#                 d[ppos] = v
#                 nv = v+1 if not vacant[ppos] else v
#                 q.append((nv, ppos))
#         if pos-n>=0:
#             ppos = pos - n
#             if d[ppos]>v:
#                 d[ppos] = v
#                 nv = v+1 if not vacant[ppos] else v
#                 q.append((nv, ppos))
#         if pos+1<n*n:
#             ppos = pos + 1
#             if d[ppos]>v:
#                 d[ppos] = v
#                 nv = v+1 if not vacant[ppos] else v
#                 q.append((nv, ppos))
#         if pos-1>=0:
#             ppos = pos - 1
#             if d[ppos]>v:
#                 d[ppos] = v
#                 nv = v+1 if not vacant[ppos] else v
#                 q.append((nv, ppos))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

d = [None] * (n**2)
for i in range(n):
    for j in range(n):
        d[i*n+j] = min(i, n-1-i, j, n-1-j)
vacant = [False] * (n**2)

ans = 0
for pos in p:
    pos -= 1
    ans += d[pos]
    v = d[pos]
    vacant[pos] = True
    q = [(v, pos)]
    while q:
        v,pos = q.pop()
        if pos+n<n*n:
            ppos = pos + n
            if d[ppos]>v:
                d[ppos] = v
                nv = v+1 if not vacant[ppos] else v
                q.append((nv, ppos))
        if pos-n>=0:
            ppos = pos - n
            if d[ppos]>v:
                d[ppos] = v
                nv = v+1 if not vacant[ppos] else v
                q.append((nv, ppos))
        if pos+1<n*n:
            ppos = pos + 1
            if d[ppos]>v:
                d[ppos] = v
                nv = v+1 if not vacant[ppos] else v
                q.append((nv, ppos))
        if pos-1>=0:
            ppos = pos - 1
            if d[ppos]>v:
                d[ppos] = v
                nv = v+1 if not vacant[ppos] else v
                q.append((nv, ppos))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
p = [int(x) for x in input().split()]

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    q = deque([(x, y)])
    while q:
        x, y = q.popleft()
        if 0 <= x+1 < n and 0 <= y < n and seat[x+1][y] > seat[x][y] + reserved[x][y]:
            seat[x+1][y] = seat[x][y] + reserved[x][y]
            q.append((x+1, y))
        if 0 <= x-1 < n and 0 <= y < n and seat[x-1][y] > seat[x][y] + reserved[x][y]:
            seat[x-1][y] = seat[x][y] + reserved[x][y]
            q.append((x-1, y))
        if 0 <= x < n and 0 <= y+1 < n and seat[x][y+1] > seat[x][y] + reserved[x][y]:
            seat[x][y+1] = seat[x][y] + reserved[x][y]
            q.append((x, y+1))
        if 0 <= x < n and 0 <= y-1 < n and seat[x][y-1] > seat[x][y] + reserved[x][y]:
            seat[x][y-1] = seat[x][y] + reserved[x][y]
            q.append((x, y-1))


print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
p = [int(x) for x in input().split()]

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    q = deque([(x, y)])
    while q:
        x, y = q.popleft()
        if 0 <= x+1 < n and 0 <= y < n and seat[x+1][y] > seat[x][y] + reserved[x][y]:
            seat[x+1][y] = seat[x][y] + reserved[x][y]
            if not reserved[x][y]:
                q.appendleft((x+1, y))
            else:
                q.append((x+1, y))
        if 0 <= x-1 < n and 0 <= y < n and seat[x-1][y] > seat[x][y] + reserved[x][y]:
            seat[x-1][y] = seat[x][y] + reserved[x][y]
            if not reserved[x][y]:
                q.appendleft((x-1, y))
            else:
                q.append((x-1, y))
        if 0 <= x < n and 0 <= y+1 < n and seat[x][y+1] > seat[x][y] + reserved[x][y]:
            seat[x][y+1] = seat[x][y] + reserved[x][y]
            if not reserved[x][y]:
                q.appendleft((x, y+1))
            else:
                q.append((x, y+1))
        if 0 <= x < n and 0 <= y-1 < n and seat[x][y-1] > seat[x][y] + reserved[x][y]:
            seat[x][y-1] = seat[x][y] + reserved[x][y]
            if not reserved[x][y]:
                q.appendleft((x, y-1))
            else:
                q.append((x, y-1))


print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

d = [None] * (n**2)
for i in range(n):
    for j in range(n):
        d[i*n+j] = min(i, n-1-i, j, n-1-j)
vacant = [False] * (n**2)

ans = 0
for pos in p:
    pos -= 1
    ans += d[pos]
    v = d[pos]
    vacant[pos] = True
    q = [(v, pos)]
    while q:
        v,pos = q.pop()
        for diff in (-n, n, -1, 1):
            ppos = pos + diff
            if ppos<0 or ppos>=n*n:
                continue
            if d[ppos]>v:
                d[ppos] = v
                nv = v+1 if not vacant[ppos] else v
                q.append((nv, ppos))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = [int(x) for x in input().split()]

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [[-1, 0], [1, 0], [0, -1], [0, 1]]

for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    q = [(x, y)]
    while q:
        x, y = q.pop()
        for dx, dy in vec:
            if 0 <= x+dx < n and 0 <= y+dy < n and seat[x+dx][y+dy] > seat[x][y] + reserved[x][y]:
                seat[x+dx][y+dy] = seat[x][y] + reserved[x][y]
                q.append((x+dx, y+dy))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = [int(x) for x in input().split()]

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    q = [(x, y)]
    while q:
        x, y = q.pop()
        for dx, dy in vec:
            if 0 <= x+dx < n and 0 <= y+dy < n and seat[x+dx][y+dy] > seat[x][y] + reserved[x][y]:
                seat[x+dx][y+dy] = seat[x][y] + reserved[x][y]
                q.append((x+dx, y+dy))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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

d = [None] * (n**2)
for i in range(n):
    for j in range(n):
        d[i*n+j] = min(i, n-1-i, j, n-1-j)
vacant = [False] * (n**2)

def sub(pos):
    v = d[pos]
    q = [(v, pos)]
    while q:
        v,pos = q.pop()
        for diff in (-n, n, -1, 1):
            ppos = pos + diff
            if ppos<0 or ppos>=n*n:
                continue
            if d[ppos]>v:
                d[ppos] = v
                nv = v+1 if not vacant[ppos] else v
                q.append((nv, ppos))
ans = 0
for v in p:
    v -= 1
    ans += d[v]
    sub(v)
    vacant[v] = True
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

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

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    q = [(x, y)]
    while q:
        x, y = q.pop()
        for dx, dy in vec:
            x1 = x+dx
            y1 = y+dy
            if 0 <= x1 < n and 0 <= y1 < n and seat[x1][y1] > seat[x][y] + reserved[x][y]:
                seat[x1][y1] = seat[x][y] + reserved[x][y]
                q.append((x1, y1))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
S=list(map(int,input().split()))
count=0
P=[0]*(N*N+1)
for j in range(N*N):
  P[S[j]]=j+1
d=[-1]*(N*N+1)
for i in range(N*N):
  player=S[i]
  hayasa=P[player]
  
  que=[[] for _ in range(N)]
  que[0].append(player)
  d[player]=i
  
  j=0
  finish=0
  while True:
    for kouho in que[j]:
      if kouho%N==0:
        finish=1
        break
      if kouho%N==1:
        finish=1
        break
      if kouho+N>N*N:
        finish=1
        break
      if kouho<N:
        finish=1
        break
        
      if d[kouho+N]<i:
        if P[kouho+N]>hayasa:
          que[j+1].append(kouho+N)
          d[kouho+N]=i
        else:
          que[j].append(kouho+N)
          d[kouho+N]=i
          
      if d[kouho-N]<i:
        if P[kouho-N]>hayasa:
          que[j+1].append(kouho-N)
          d[kouho-N]=i
        else:
          que[j].append(kouho-N)
          d[kouho-N]=i
          
      if d[kouho+1]<i:
        if P[kouho+1]>hayasa:
          que[j+1].append(kouho+1)
          d[kouho+1]=i
        else:
          que[j].append(kouho+1)
          d[kouho+1]=i
          
      if d[kouho-1]<i:
        if P[kouho-1]>hayasa:
          que[j+1].append(kouho-1)
          d[kouho-1]=i
        else:
          que[j].append(kouho-1)
          d[kouho-1]=i
    if finish==1:
      count+=j
      break
    j+=1    
print(count)

Submission status: Time Limit Exceeded

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

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    q = [(x, y)]
    while q:
        x, y = q.pop()
        for dx, dy in vec:
            x1 = x+dx
            y1 = y+dy
            if 0 <= x1 < n and 0 <= y1 < n and seat[x1][y1] > seat[x][y] + reserved[x][y]:
                seat[x1][y1] = seat[x][y] + reserved[x][y]
                q.append((x1, y1))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def solve():
    n = int(input())
    p = [int(x) for x in input().split()]

    ans = 0
    seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
    reserved = [[True for j in range(n)] for i in range(n)]

    vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    for i in range(n**2):
        v = p[i]-1
        x, y = v//n, v % n
        reserved[x][y] = False
        ans += seat[x][y]
        q = [(x, y)]
        while q:
            x, y = q.pop()
            for dx, dy in vec:
                x1 = x+dx
                y1 = y+dy
                if 0 <= x1 < n and 0 <= y1 < n and seat[x1][y1] > seat[x][y] + reserved[x][y]:
                    seat[x1][y1] = seat[x][y] + reserved[x][y]
                    q.append((x1, y1))
    print(ans)


solve()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = [int(x) for x in input().split()]

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]


def bfs(x, y):
    q = [(x, y)]
    while q:
        x, y = q.pop()
        for dx, dy in vec:
            x1 = x+dx
            y1 = y+dy
            if 0 <= x1 < n and 0 <= y1 < n and seat[x1][y1] > seat[x][y] + reserved[x][y]:
                seat[x1][y1] = seat[x][y] + reserved[x][y]
                q.append((x1, y1))


for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    bfs(x, y)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = [int(x) for x in input().split()]

ans = 0
seat = [[min(i, j, n-i-1, n-j-1) for j in range(n)] for i in range(n)]
reserved = [[True for j in range(n)] for i in range(n)]

vec = [(-1, 0), (1, 0), (0, -1), (0, 1)]


def bfs(x, y):
    q = [(x, y)]
    while q:
        x, y = q.pop()
        for dx, dy in vec:
            x1 = x+dx
            y1 = y+dy
            if 0 <= x1 < n and 0 <= y1 < n and seat[x1][y1] > seat[x][y]:
                seat[x1][y1] = seat[x][y] + reserved[x][y]
                q.append((x1, y1))


for i in range(n**2):
    v = p[i]-1
    x, y = v//n, v % n
    reserved[x][y] = False
    ans += seat[x][y]
    bfs(x, y)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from numba import njit, jit, int32
import numpy as np
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
# p = list(map(int, input().split()))
p = np.array(input().split(), dtype=np.int32)


@njit('(i4,i4[::1])', cache=True)
def main(n, p):
#     d = [[None]*n for _ in range(n)]
    d = np.zeros((n,n), dtype=np.int32)
    for i in range(n):
        for j in range(n):
            d[i,j] = min(i, n-1-i, j, n-1-j)
#     vacant = [[False]*n for _ in range(n)]
    vacant = np.zeros((n,n), dtype=np.int32)

    ans = 0
    for v in p:
        v -= 1
        x,y = v//n, v%n
        ans += d[x,y]
    #     print(v, d[x][y], d)
        v = d[x,y]
        q = [(v, x, y)]
        dx = [0,1,0,-1]
        dy = [1,0,-1,0]
        while q:
            v,i,j = q.pop()
            for xx, yy in zip(dx,dy):
                ii = i+xx
                jj = j+yy
                if ii<0 or jj<0 or ii>=n or jj>=n:
                    continue
                if d[ii,jj]>v:
                    d[ii,jj] = v
                    nv = v+1 if not vacant[ii,jj] else v
                    q.append((nv, ii, jj))

        vacant[x,y] = 1
    return ans
ans = main(n,p)
print(ans)