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:
n = int(input())
p = list(map(int,input().split()))

ans = 0

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0]*(n+1)
        self.depth = n.bit_length()

    def __iter__(self):
        psum = 0
        for i in range(self.size):
            csum = self.sum(i+1)
            yield csum - psum
            psum = csum
        raise StopIteration()

    def __str__(self):  # O(nlogn)
        return str(list(self))

    def sum(self, i):
        # [0, i) の要素の総和を返す
        if not (0 <= i <= self.size): raise ValueError("error!")
        s = 0
        while i>0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        if not (0 <= i < self.size): raise ValueError("error!")
        i += 1
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

    def lower_bound(self, x):
        """ 累積和がx以上になる最小のindexと、その直前までの累積和 """
        sum_ = 0
        pos = 0
        for i in range(self.depth, -1, -1):
            k = pos + (1 << i)
            if k <= self.size and sum_ + self.tree[k] < x:
                sum_ += self.tree[k]
                pos += 1 << i
        return pos + 1, sum_

    def __getitem__(self, key):
        if not (0 <= key < self.size): raise IndexError("error!")
        return self.sum(key+1) - self.sum(key)

    def __setitem__(self, key, value):
        # 足し算と引き算にはaddを使うべき
        if not (0 <= key < self.size): raise IndexError("error!")
        self.add(key, value - self[key])

class BitImos:
    """
    ・範囲すべての要素に加算
    ・ひとつの値を取得
    の2種類のクエリをO(logn)で処理
    bit = BitImos(len(li))
    """
    def __init__(self, n):
        self.bit = Bit(n+1)

    def add(self, s, t, x):
        # [s, t)にxを加算
        self.bit.add(s, x)
        self.bit.add(t, -x)

    def get(self, i):
        return self[i]

    def __getitem__(self, key):
        # 位置iの値を取得
        return self.bit.sum(key+1)

bita = BitImos(n**2)
bitb = BitImos(n**2)
bitc = BitImos(n**2)
bitd = BitImos(n**2)

for i in range(n):
    for j in range(n):
        bita.add(1+j+i*n,n + i*n,1)
for i in range(n):
    for j in range(n):
        bitb.add(1+j+i*n,n + i*n,1)
for i in range(n):
    for j in range(n):
        bitc.add(1+j+i*n,n + i*n,1)
for i in range(n):
    for j in range(n):
        bitd.add(1+j+i*n,n + i*n,1)

for i in p:
    i -= 1
    k = i % n
    j = i // n
    ans += min(bita.get(k*n+j), bitb.get(k*n+n-j-1), bitc.get(j*n+k), bitd.get(j*n+n-k-1))
    bita.add(k*n+j+1, (k+1)*n,-1)
    bitb.add((k+1)*n-j, (k+1)*n,-1)
    bitc.add(j*n+k+1, (j+1)*n,-1)
    bitd.add((j+1)*n-k, (j+1)*n,-1)

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
n = int(input())
P = list(map(int,input().split()))
zaseki = np.array([[1] * n for i in [1]*n])
ans = 0
for i in P:
    x = i%n-1
    y = (i-1)//n
    zaseki[y][x] = 0
    ans += min(sum(zaseki[y,:1+x]), sum(zaseki[y,x:]), sum(zaseki[:y+1,x]), sum(zaseki[y:,x]))
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
P = list(map(int,input().split()))

Submission status: Wrong Answer

Solution code:
cin = open(0).read().strip().split('\n')
n = int(cin[0])
p = list(map(int, cin[1].split(' ')))

import numpy as np
seet = np.arange(n*n).reshape(n,n)
dist = np.ones(n*n).reshape(n,n)

ans = 0
for pi in p:
    row, col = divmod(pi-1, n)
    hor = min(dist[:row, col].sum(), dist[row+1:, col].sum())
    var = min(dist[row, :col].sum(), dist[row, col+1:].sum())
    if row==1 and col==1:
        aaaa = dist
    ans += min(hor, var)
    dist[row][col] = 0

print(int(ans))

Submission status: Wrong Answer

Solution code:
print(1)

Submission status: Time Limit Exceeded

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

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

exist=[[1]*n for _ in range(n)]
dxy=[(0,1),(1,0),(-1,0),(0,-1)]

ans=0
q=deque()
for pi in p:
    ans+=seats[pi//n][pi%n]
    exist[pi//n][pi%n]=0
    q.append((pi//n,pi%n))
    while q:
        i,j=q.popleft()
        for dx,dy in dxy:
            idx=i+dx;jdy=j+dy
            if 0<=idx<n and 0<=jdy<n:
                if seats[i][j]+exist[i][j]<seats[idx][jdy]:
                    seats[idx][jdy]=seats[i][j]+exist[i][j]
                    q.append((idx,jdy))


print(ans)

Submission status: Time Limit Exceeded

Solution code:

def main(n,p):
  sheet=[min(i%n,i//n,n-i%n-1,n-i//n-1) for i in range(n**2)]
  space=[1]*(n**2)
  ans=0
  for x in p:
    x-=1
    ans+=sheet[x]
    space[x]=0
    todo=[(x,sheet[x])]
    while todo:
      v,c=todo.pop()
      x,y=divmod(v,n)
      for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
        if 0<=x+dx<n and 0<=y+dy<n:
          nv=(x+dx)*n+(y+dy)
          if sheet[nv]>c:
            sheet[nv]=c
            todo.append((nv,c+space[nv]))
  print(ans)

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

Submission status: Time Limit Exceeded

Solution code:

def dfs(c,v,sheet,space,n):
  todo=[(v,c)]
  while todo:
    v,c=todo.pop()
    x,y=divmod(v,n)
    for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
      if 0<=x+dx<n and 0<=y+dy<n:
        nv=(x+dx)*n+(y+dy)
        if sheet[nv]>c:
          sheet[nv]=c
          todo.append((nv,c+space[nv]))

def main(n,p):
  sheet=[min(i%n,i//n,n-i%n-1,n-i//n-1) for i in range(n**2)]
  space=[1]*(n**2)
  ans=0
  for x in p:
    x-=1
    ans+=sheet[x]
    space[x]=0
    dfs(sheet[x],x,sheet,space,n)
  print(ans)

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

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
import numpy as np
import sys
input = sys.stdin.buffer.readline

@njit('i4, i4, i4, i4[:,:], i4[:,:]')
def dfs(N, h, w, minDist, isFilled):
    dist = minDist[h][w] + isFilled[h][w]

    if h + 1 < N and minDist[h + 1][w] > dist:
        minDist[h + 1][w] = dist
        dfs(N, h + 1, w, minDist, isFilled)
    if h - 1 >= 0 and minDist[h - 1][w] > dist:
        minDist[h - 1][w] = dist
        dfs(N, h - 1, w, minDist, isFilled)
    if w + 1 < N and minDist[h][w + 1] > dist:
        minDist[h][w + 1] = dist
        dfs(N, h, w + 1, minDist, isFilled)
    if w - 1 < N and minDist[h][w - 1] > dist:
        minDist[h][w - 1] = dist
        dfs(N, h, w - 1, minDist, isFilled)

@njit('i4(i4, i4[:])')
def solve(N, P):
    minDist = np.ones((N, N), dtype=np.int32)
    isFilled = np.ones((N, N), dtype=np.int32)

    for h in range(N):
        for w in range(N):
            minDist[h][w] = min(h, N - h - 1, w, N - w - 1)

    ans = 0
    for p in P:
        h, w = divmod(p, N)
        ans += minDist[h][w]
        isFilled[h][w] = False
        dfs(N, h, w, minDist, isFilled)
    return ans

N = int(input())
P = np.asarray(list(map(lambda a: int(a) - 1, input().split())), dtype=np.int32)

print(solve(N, P))

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC
    cc = CC('my_module')

    @cc.export('solve', 'i4(i4, i4[:])')
    def solve(N, P):
        minDist = np.ones((N, N), dtype=np.int32)
        isFilled = np.ones((N, N), dtype=np.int32)

        for h in range(N):
            for w in range(N):
                minDist[h][w] = min(h, N - h - 1, w, N - w - 1)

        ans = 0
        for p in P:
            h, w = divmod(p, N)
            ans += minDist[h][w]
            isFilled[h][w] = False

            st = [[h, w]]
            while st:
                h, w = st.pop()
                dist = minDist[h][w] + isFilled[h][w]

                if h + 1 < N and minDist[h + 1][w] > dist:
                    minDist[h + 1][w] = dist
                    st.append([h + 1, w])
                if h - 1 >= 0 and minDist[h - 1][w] > dist:
                    minDist[h - 1][w] = dist
                    st.append([h - 1, w])
                if w + 1 < N and minDist[h][w + 1] > dist:
                    minDist[h][w + 1] = dist
                    st.append([h, w + 1])
                if w - 1 < N and minDist[h][w - 1] > dist:
                    minDist[h][w - 1] = dist
                    st.append([h, w - 1])
        return ans

    cc.compile()
    exit(0)

from my_module import solve

N = int(input())
P = np.asarray(list(map(lambda a: int(a) - 1, input().split())), dtype=np.int32)

print(solve(N, P))

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
import numpy as np

@njit('i4, i4, i4, i4[:,:], i4[:,:]')
def dfs(N, h, w, minDist, isFilled):
    dist = minDist[h][w] + isFilled[h][w]

    if h + 1 < N and minDist[h + 1][w] > dist:
        minDist[h + 1][w] = dist
        dfs(N, h + 1, w, minDist, isFilled)
    if h - 1 >= 0 and minDist[h - 1][w] > dist:
        minDist[h - 1][w] = dist
        dfs(N, h - 1, w, minDist, isFilled)
    if w + 1 < N and minDist[h][w + 1] > dist:
        minDist[h][w + 1] = dist
        dfs(N, h, w + 1, minDist, isFilled)
    if w - 1 < N and minDist[h][w - 1] > dist:
        minDist[h][w - 1] = dist
        dfs(N, h, w - 1, minDist, isFilled)

@njit('i4(i4, i4[:])')
def solve(N, P):
    minDist = np.ones((N, N), dtype=np.int32)
    isFilled = np.ones((N, N), dtype=np.int32)

    for h in range(N):
        for w in range(N):
            minDist[h][w] = min(h, N - h - 1, w, N - w - 1)

    ans = 0
    for p in P:
        h, w = divmod(p, N)
        ans += minDist[h][w]
        isFilled[h][w] = False
        dfs(N, h, w, minDist, isFilled)
    return ans

N = int(input())
P = np.asarray(list(map(lambda a: int(a) - 1, input().split())), dtype=np.int32)

print(solve(N, P))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

def pToHW(p):
    p = int(p) - 1
    return divmod(p, N)

P = list(map(pToHW, input().split()))
INF = 10**18

minDist = [[INF] * N for _ in range(N)]
isFilled = [[True] * N for _ in range(N)]

def dfs(h, w):
    st = [(h, w)]
    while st:
        h, w = st.pop()
        dist = minDist[h][w] + (1 if isFilled[h][w] else 0)
        for toH, toW in ((h + 1, w), (h - 1, w), (h, w + 1), (h, w - 1)):
            if 0 <= toH < N and 0 <= toW < N:
                if minDist[toH][toW] > dist:
                    minDist[toH][toW] = dist
                    st.append((toH, toW))

for h in range(N):
    for w in range(N):
        minDist[h][w] = min(h, N - h - 1, w, N - w - 1)

ans = 0
for h, w in P:
    ans += minDist[h][w]
    isFilled[h][w] = False
    dfs(h, w)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

def pToHW(p):
    p = int(p) - 1
    return divmod(p, N)

P = list(map(pToHW, input().split()))
INF = 10**18

minDist = [[INF] * N for _ in range(N)]
isFilled = [[True] * N for _ in range(N)]


def dfs(h, w):
    st = [(h, w)]
    while st:
        h, w = st.pop()
        dist = minDist[h][w] + (1 if isFilled[h][w] else 0)
        for toH, toW in ((h + 1, w), (h - 1, w), (h, w + 1), (h, w - 1)):
            if 0 <= toH < N and 0 <= toW < N:
                if minDist[toH][toW] > dist:
                    minDist[toH][toW] = dist
                    st.append((toH, toW))

for i in range(N):
    minDist[i][0] = 0
    minDist[0][i] = 0
    minDist[i][N - 1] = 0
    minDist[N - 1][i] = 0

for i in range(N):
    dfs(i, 0)
    dfs(0, i)
    dfs(i, N - 1)
    dfs(N - 1, i)

ans = 0
for h, w in P:
    ans += minDist[h][w]
    isFilled[h][w] = False
    dfs(h, w)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10**7)

N = int(input())

def pToHW(p):
    p = int(p) - 1
    return divmod(p, N)

P = list(map(pToHW, input().split()))
INF = 10**18

minDist = [[INF] * N for _ in range(N)]
isFilled = [[True] * N for _ in range(N)]


def dfs(h, w):
    dist = minDist[h][w] + (1 if isFilled[h][w] else 0)
    for toH, toW in ((h + 1, w), (h - 1, w), (h, w + 1), (h, w - 1)):
        if 0 <= toH < N and 0 <= toW < N:
            if minDist[toH][toW] > dist:
                minDist[toH][toW] = dist
                dfs(toH, toW)

for i in range(N):
    minDist[i][0] = 0
    minDist[0][i] = 0
    minDist[i][N - 1] = 0
    minDist[N - 1][i] = 0
for i in range(N):
    dfs(i, 0)
    dfs(0, i)
    dfs(i, N - 1)
    dfs(N - 1, i)

ans = 0
for h, w in P:
    ans += minDist[h][w]
    isFilled[h][w] = False
    dfs(h, w)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())

def pToHW(p):
    p = int(p) - 1
    return divmod(p, N)

P = list(map(pToHW, input().split()))

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

def calcDist():
    minDist = [[10**18] * N for _ in range(N)]
    que = deque([])
    for h in range(N):
        if isFilled[h][0]:
            que.append((h, 0, 1))
        else:
            que.appendleft((h, 0, 0))
        if isFilled[h][N - 1]:
            que.append((h, N - 1, 1))
        else:
            que.appendleft((h, N - 1, 0))
    for w in range(1, N - 1):
        if isFilled[0][w]:
            que.append((0, w, 1))
        else:
            que.appendleft((0, w, 0))
        if isFilled[N - 1][w]:
            que.append((N - 1, w, 1))
        else:
            que.appendleft((N - 1, w, 0))

    while que:
        h, w, dist = que.popleft()

        if minDist[h][w] < dist:
            continue
        minDist[h][w] = dist

        for toH, toW in ((h + 1, w), (h - 1, w), (h, w + 1), (h, w - 1)):
            if not (0 <= toH < N and 0 <= toW < N):
                continue

            d = dist
            if isFilled[toH][toW]:
                d += 1

            if minDist[toH][toW] > d:
                minDist[toH][toW] = d
                if isFilled[toH][toW]:
                    que.append((toH, toW, d))
                else:
                    que.appendleft((toH, toW, d))

    return minDist

ans = 0
for h, w in P[::-1]:
    ans += calcDist()[h][w]
    isFilled[h][w] = True
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())

def pToHW(p):
    p = int(p) - 1
    return divmod(p, N)

P = list(map(pToHW, input().split()))

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

def calcDist():
    minDist = [[10**18] * N for _ in range(N)]
    que = deque([])
    for h in range(N):
        if isFilled[h][0]:
            que.append((h, 0, 1))
        else:
            que.appendleft((h, 0, 0))
        if isFilled[h][N - 1]:
            que.append((h, N - 1, 1))
        else:
            que.appendleft((h, N - 1, 0))
    for w in range(1, N - 1):
        if isFilled[0][w]:
            que.append((0, w, 1))
        else:
            que.appendleft((0, w, 0))
        if isFilled[N - 1][w]:
            que.append((N - 1, w, 1))
        else:
            que.appendleft((N - 1, w, 0))

    while que:
        h, w, dist = que.popleft()

        if minDist[h][w] <= dist:
            continue
        minDist[h][w] = dist

        for toH, toW in ((h + 1, w), (h - 1, w), (h, w + 1), (h, w - 1)):
            if not (0 <= toH < N and 0 <= toW < N):
                continue

            if isFilled[toH][toW]:
                que.append((toH, toW, dist + 1))
            else:
                que.appendleft((toH, toW, dist))
    return minDist

ans = 0
for h, w in P[::-1]:
    ans += calcDist()[h][w]
    isFilled[h][w] = True
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N = int(input())

def pToHW(p):
    p = int(p) - 1
    return divmod(p, N)

P = list(map(pToHW, input().split()))

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

def calcDist():
    minDist = [[10**18] * N for _ in range(N)]
    que = deque([])
    for h in range(N):
        if isFilled[h][0]:
            que.append((h, 0, 1))
        else:
            que.appendleft((h, 0, 0))
        if isFilled[h][N - 1]:
            que.append((h, N - 1, 1))
        else:
            que.appendleft((h, N - 1, 0))
    for w in range(1, N - 1):
        if isFilled[0][w]:
            que.append((0, w, 1))
        else:
            que.appendleft((0, w, 0))
        if isFilled[N - 1][w]:
            que.append((N - 1, w, 1))
        else:
            que.appendleft((N - 1, w, 0))

    while que:
        h, w, dist = que.popleft()

        if minDist[h][w] <= dist:
            continue
        minDist[h][w] = dist

        for toH, toW in ((h + 1, w), (h - 1, w), (h, w + 1), (h, w - 1)):
            if not (0 <= toH < N and 0 <= toW < N):
                continue

            if isFilled[toH][toW]:
                que.append((toH, toW, dist + 1))
            else:
                que.append((toH, toW, dist))
    return minDist

ans = 0
for h, w in P[::-1]:
    ans += calcDist()[h][w]
    isFilled[h][w] = True
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n = int(input())
P = list(int(x) - 1 for x in input().split())
A = [0] * (n**2)
remain = [1] * (n**2)

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

ans = 0
for i in range(n**2):
    ans += A[P[i]]
    remain[P[i]] = 0
    que = deque([P[i]])
    visited = [False] * (n**2)
    while que:
        k = que.popleft()
        visited[k] = True
        if k % n != 0:  # left
            nk = k - 1
            if not visited[nk]:
                A[nk] = min(A[nk], A[k] + remain[k])
                que.append(nk)
        if n - (k % n) - 1 != 0:  # right
            nk = k + 1
            if not visited[nk]:
                A[nk] = min(A[nk], A[k] + remain[k])
                que.append(nk)
        if k // n != 0:  # up
            nk = k - n
            if not visited[nk]:
                A[nk] = min(A[nk], A[k] + remain[k])
                que.append(nk)
        if n - (k // n) - 1 != 0:  # down
            nk = k + n
            if not visited[nk]:
                A[nk] = min(A[nk], A[k] + remain[k])
                que.append(nk)

print(ans)

Submission status: Time Limit Exceeded

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

def main():
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N = NI()
    P = LI()

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

    r = [[1] * N for _ in range(N)]

    ans = 0
    q = []
    for p in P:
        x = (p-1)//N
        y = (p-1) % N
        ans += s[x][y]
        r[x][y] = 0
        q.append((x,y))
        while q:
            a,b = q.pop()
            nc = s[a][b] + r[a][b]
            for da,db in ((1,0),(0,1),(-1,0),(0,-1)):
                na = a + da; nb = b + db
                if 0 < na < N-1 and 0 < nb < N-1:
                    if s[na][nb] <= nc: continue
                    s[na][nb] = nc
                    q.append((na,nb))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def main():
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N = NI()
    P = LI()

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

    r = [[1] * N for _ in range(N)]

    ans = 0
    q = collections.deque()
    for p in P:
        x = (p-1)//N
        y = (p-1) % N
        ans += s[x][y]
        r[x][y] = 0
        q.append((x,y))
        while q:
            a,b = q.pop()
            nc = s[a][b] + r[a][b]
            for da,db in ((1,0),(0,1),(-1,0),(0,-1)):
                na = a + da; nb = b + db
                if 0 < na < N-1 and 0 < nb < N-1:
                    if s[na][nb] <= nc: continue
                    s[na][nb] = nc
                    q.append((na,nb))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def main():
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N = NI()
    P = LI()

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

    r = [[1] * N for _ in range(N)]

    ans = 0
    for p in P:
        x = (p-1)//N
        y = (p-1) % N
        ans += s[x][y]
        r[x][y] = 0
        q = collections.deque()
        q.append((x,y))
        while q:
            a,b = q.pop()
            nc = s[a][b] + r[a][b]
            for da,db in ((1,0),(0,1),(-1,0),(0,-1)):
                na = a + da; nb = b + db
                if 0 < na < N-1 and 0 < nb < N-1:
                    if s[na][nb] <= nc: continue
                    s[na][nb] = nc
                    q.append((na,nb))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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

    N = NI()
    P = LI()

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

    r = [[1] * N for _ in range(N)]

    ans = 0
    for p in P:
        x = (p-1)//N
        y = (p-1) % N
        ans += s[x][y]
        r[x][y] = 0
        q = collections.deque()
        q.append((x,y,s[x][y]))
        while q:
            a,b,c = q.pop()
            nc = c + r[a][b]
            for da,db in ((1,0),(0,1),(-1,0),(0,-1)):
                na = a + da; nb = b + db
                if 0 < na < N-1 and 0 < nb < N-1:
                    if s[na][nb] <= nc: continue
                    s[na][nb] = nc
                    q.append((na,nb,nc))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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

    N = NI()
    P = LI()

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

    r = [[1] * N for _ in range(N)]

    ans = 0
    for p in P:
        x = (p-1)//N
        y = (p-1) % N
        ans += s[x][y]
        r[x][y] = 0
        q = collections.deque()
        q.append((x,y,s[x][y]))
        while q:
            a,b,c = q.pop()
            nc = c + r[a][b]
            for da,db in ((1,0),(0,1),(-1,0),(0,-1)):
                na = a + da; nb = b + db
                if 0 <= na < N and 0 <= nb < N:
                    if s[na][nb] <= nc: continue
                    s[na][nb] = nc
                    q.append((na,nb,nc))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
def resolve():
    n = int(input())
    dp = [[0] * n for _ in range(n)]
    used = [[True] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            dp[i][j] = min(i, j, n - i - 1, n - j - 1)

    ans = 0
    for p in map(lambda x : int(x) - 1, input().split()):
        i, j = divmod(p, n)
        ans += dp[i][j]
        used[i][j] = False
        # dfs
        stack = [(i, j)]
        D = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        while stack:
            i, j = stack.pop()
            for di, dj in D:
                ni, nj = i + di, j + dj
                if not (0 <= ni < n and 0 <= nj < n):
                    continue
                if dp[ni][nj] > dp[i][j] + used[i][j]:
                    dp[ni][nj] = dp[i][j] + used[i][j]
                    stack.append((ni, nj))

    print(ans)
resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
from collections import deque, defaultdict
def resolve():
    n = int(input())
    ans = 0
    grid = [[1] * n for _ in range(n)]
    D = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    for p in map(lambda x : int(x) - 1, input().split()):
        i, j = divmod(p, n)
        grid[i][j] = 0
        dist = defaultdict(lambda:INF)
        dist[i, j] = 0
        Q = deque([(i, j)])

        while Q:
            i, j = Q.popleft()
            if i in (0, n - 1) or j in (0, n - 1):
                ans += dist[i, j]
                break
            for di, dj in D:
                ni, nj = i + di, j + dj
                if not (0 <= ni < n and 0 <= nj < n):
                    continue
                if dist[ni, nj] > dist[i, j] + grid[ni][nj]:
                    dist[ni, nj] = dist[i, j] + grid[ni][nj]
                    if grid[ni][nj] == 0:
                        Q.appendleft((ni, nj))
                    else:
                        Q.append((ni, nj))

    print(ans)
resolve()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
from collections import deque

n = int(input())

field = [[-1] * (n + 2)]
for _ in range(n):
    field.append([-1] + [1] * n + [-1])
field.append([-1] * (n + 2))
p = [int(item) - 1 for item in input().split()]


dxs = [0, 1, 0, -1]
dys = [1, 0, -1, 0]

def bfs(x, y):
    dq = deque()
    dq.append((x, y, 0))
    visited = [[0] * (n + 2) for _ in range(n + 2)]
    visited[x][y] = 1
    field[x][y] = 0
    while dq:
        x, y, d = dq.popleft()
        for dx, dy in zip(dxs, dys):
            nx = x + dx; ny = y + dy
            if visited[nx][ny]:
                continue
            if field[nx][ny] == -1:
                return d
            visited[nx][ny] = 1
            if field[nx][ny] == 0:
                dq.appendleft((nx, ny, d))
            else:
                dq.append((nx, ny, d + 1))

ans = 0
for item in p:
    i = item // n
    j = item % n
    ans += bfs(i + 1, j + 1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
from collections import deque

n = int(input())

field = [[-1] * (n + 2)]
for _ in range(n):
    field.append([-1] + [1] * n + [-1])
field.append([-1] * (n + 2))
p = [int(item) - 1 for item in input().split()]


dxs = [0, 1, 0, -1]
dys = [1, 0, -1, 0]

def bfs(x, y):
    dq = deque()
    dq.append(x)
    dq.append(y)
    dq.append(0)
    visited = [[0] * (n + 2) for _ in range(n + 2)]
    visited[x][y] = 1
    field[x][y] = 0
    while dq:
        x = dq.popleft()
        y = dq.popleft()
        d = dq.popleft()
        for dx, dy in zip(dxs, dys):
            nx = x + dx; ny = y + dy
            if visited[nx][ny]:
                continue
            if field[nx][ny] == -1:
                return d
            visited[nx][ny] = 1
            if field[nx][ny] == 0:
                dq.appendleft(d)
                dq.appendleft(ny)
                dq.appendleft(nx)
            else:
                dq.append(nx)
                dq.append(ny)
                dq.append(d + 1)

ans = 0
for item in p:
    i = item // n
    j = item % n
    ans += bfs(i + 1, j + 1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from numba import njit
import numpy as np
@njit
def dfs(v,c,h,stay):
    # hを更新
    todo=[[v,c]]
    todo=np.zeros((n*n,2),np.int32)
    todo[0][0]=v
    todo[0][1]=c
    now=0
    while now>=0:
        vv,cc=todo[now]
        now-=1
        x,y=divmod(vv,n)
        for dx,dy in ((0,1),(0,-1),(1,0),(-1,0)):
            nx,ny=x+dx,y+dy
            if 0<=nx<n and 0<=ny<n:
                nv=nx*n+ny
                if h[nv]>cc:
                    h[nv]=cc
                    now+=1
                    todo[now][0]=nv
                    todo[now][1]=cc+stay[nv]

@njit
def main(n,p):
    h=[min(i//n,n-i//n-1,i%n,n-i%n-1) for i in range(n**2)]
    h=np.array(h,np.int32)
    stay=np.full(n*n,1,np.int32)
    ans=0

    for v in p:
        c=h[v]
        ans+=c
        stay[v]=0
        dfs(v,c,h,stay)
    print(ans)

if __name__=='__main__':
    n=int(input())
    p=np.array(list(map(int,input().split())),np.int32)
    p-=1
    main(n,p)