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
# Author: lee215

import sys
sys.setrecursionlimit(10**6)

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

n = get()
A = gets()


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


occ = [[1] * n for i in xrange(n)]


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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n = I()
P = LI()
L = [[min(x, y, n - x - 1, n - y - 1) for x in range(n)] for y in range(n)]
flg = [[1] * n for _ in range(n)]
ans = 0
for i in P:
    xi = (i - 1) % n
    yi = (i - 1) // n
    ans += L[yi][xi]
    flg[yi][xi] = 0
    q = deque([i - 1])
    while q:
        l = q.popleft()
        a, b = l // n, l % n
        for j, k in ((0, 1), (1, 0), (-1, 0), (0, -1)):
            ai, bi = a + j, b + k
            if 0 <= ai < n and 0 <= bi < n and L[ai][bi] > L[a][b] + flg[a][b]:
                L[ai][bi] = L[a][b] + flg[a][b]
                q += [(ai * n + bi)]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    import sys
    input = sys.stdin.readline
    n = int(input())
    l = list(map(int,input().split()))
    check = [[1]*n for i in range(n)]
    d = [[float("INF")]*n for i in range(n)]

    for i in range((n+1)//2):
        for j in range(i,n-i):
            d[i][j] = i
            d[-1-i][j] = i
        for j in range(i,n-i):
            d[j][i] = i
            d[j][-1-i] = i

    ans = 0
    for t in l:
        t -=1
        x = t//n
        y = t%n
        check[x][y] = 0
        ans += d[x][y]
        q = deque([])
        q.append((x,y,d[x][y]))
        while q:
            bx,by,z = q.popleft()

            if bx != 0:
                if d[bx-1][by] > z:
                    d[bx-1][by] = z
                    q.append((bx-1,by,z+check[bx-1][by]))
            if bx != n-1:
                if d[bx+1][by] > z:
                    d[bx+1][by] = z
                    q.append((bx+1,by,z+check[bx+1][by]))
            if by != 0:
                if d[bx][by-1] > z:
                    d[bx][by-1] = z
                    q.append((bx,by-1,z+check[bx][by-1]))
            if by != n-1:
                if d[bx][by+1] > z:
                    d[bx][by+1] = z
                    q.append((bx,by+1,z+check[bx][by+1]))  
    print(ans)
if __name__ =="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n = I()
P = LI()
L = [[min(x, y, n - x - 1, n - y - 1) for x in range(n)] for y in range(n)]
flg = [[1] * n for _ in range(n)]
ans = 0
for i in P:
    xi = (i - 1) % n
    yi = (i - 1) // n
    ans += L[yi][xi]
    flg[yi][xi] = 0
    q = deque([(yi, xi)])
    while q:
        a, b = q.popleft()
        for j, k in ((0, 1), (1, 0), (-1, 0), (0, -1)):
            ai, bi = a + j, b + k
            if 0 <= ai < n and 0 <= bi < n and L[ai][bi] > L[a][b] + flg[a][b]:
                L[ai][bi] = L[a][b] + flg[a][b]
                q += [(ai, bi)]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    import sys
    input = sys.stdin.readline
    n = int(input())
    l = list(map(int,input().split()))
    check = [[1]*n for i in range(n)]
    d = [[float("INF")]*n for i in range(n)]

    for i in range((n+1)//2):
        for j in range(i,n-i):
            d[i][j] = i
            d[-1-i][j] = i
        for j in range(i,n-i):
            d[j][i] = i
            d[j][-1-i] = i
    def solve(l):
        ans = 0
        for t in l:
            t -=1
            x = t//n
            y = t%n
            check[x][y] = 0
            ans += d[x][y]
            q = deque([])
            q.append((x,y))
            while q:
                bx,by = q.popleft()

                if bx != 0:
                    if d[bx-1][by] > d[bx][by]+check[bx][by]:
                        d[bx-1][by] = d[bx][by]+check[bx][by]
                        q.append((bx-1,by))
                if bx != n-1:
                    if d[bx+1][by] > d[bx][by]+check[bx][by]:
                        d[bx+1][by] = d[bx][by]+check[bx][by]
                        q.append((bx+1,by))
                if by != 0:
                    if d[bx][by-1] > d[bx][by]+check[bx][by]:
                        d[bx][by-1] = d[bx][by]+check[bx][by]
                        q.append((bx,by-1))
                if by != n-1:
                    if d[bx][by+1] > d[bx][by]+check[bx][by]:
                        d[bx][by+1] = d[bx][by]+check[bx][by]
                        q.append((bx,by+1))  
        return ans

    
    print(solve(l))

if __name__ =="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
mod = 1000000007
m = [(0, 1), (1, 0), (-1, 0), (0, -1)]
inf = float('INF')

#solve
def solve():
    n = II()
    p = LI()
    dp = [min(i, j, n - i - 1, n - j - 1) for i in range(n) for j in range(n)]
    c = [1 for i in range(n) for j in range(n)]
    d = defaultdict(tuple)
    for i in range(-1, n + 1):
        for j in range(n):
            d[i * n + j] = (i, j)
    q = [0] * (n ** 2)
    ans = 0
    for pi in p:
        pi -= 1
        ans += dp[pi]
        c[pi] = 0
        q[0] = pi
        p = 0
        l = 1
        while p != l:
            yx = q[p]
            p += 1
            score = dp[yx] + c[yx]
            y, x = d[yx]
            if 0 < y < n - 1:
                if 0 < x < n - 1:
                    myx = yx + n
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx - n
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx - 1
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                    myx = yx + 1
                    if dp[myx] > score:
                        dp[myx] = score
                        q[l] = myx
                        l += 1
                else:
                    if x == 0:
                        myx = yx + 1
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
                    elif x == n - 1:
                        myx = yx - 1
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
            else:
                if y == 0:
                    if 0 < x < n - 1:
                        myx = yx + n
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
                elif y == n - 1:
                    if 0 < x < n - 1:
                        myx = yx - n
                        if dp[myx] > score:
                            dp[myx] = score
                            q[l] = myx
                            l += 1
    print(ans)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    import sys
    input = sys.stdin.readline
    n = int(input())
    l = list(map(int,input().split()))
    check = [[1]*n for i in range(n)]
    d = [[float("INF")]*n for i in range(n)]

    dx = [1,-1,0,0]
    dy = [0,0,1,-1]
    for i in range((n+1)//2):
        for j in range(i,n-i):
            d[i][j] = i
            d[-1-i][j] = i
        for j in range(i,n-i):
            d[j][i] = i
            d[j][-1-i] = i
    def update(x,y):
        check[x][y] = 0
        for i in range(4):
            nx = x+dx[i]
            ny = y+dy[i]
            if 0 <= nx < n and 0 <= ny < n:
                d[x][y] = min(d[x][y],d[nx][ny]+check[nx][ny])
        q = deque([])
        q.append((x,y))
        while q:
            bx,by = q.popleft()

            for i in range(4):
                nx = bx+dx[i]
                ny = by+dy[i]

                if 0 <= nx < n and 0 <= ny < n:
                    if d[nx][ny] > d[bx][by]+check[bx][by]:
                        d[nx][ny] = d[bx][by]+check[bx][by]
                        q.append((nx,ny))
                    

    ans = 0
    for i in l:
        i -= 1
        x = i//n
        y = i%n
        ans += d[x][y]
        update(x,y)
    print(ans)

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

def main():
    N = ir()
    P = lr()
    P = [((p-1)//N, (p-1)%N) for p in P]
    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
    for i, j in P:
        answer += dp[i][j]
        people[i][j] = False
        que = deque([(i, j, dp[i][j])])
        popleft = que.popleft; append = que.append
        while que:
            y, x, cur = popleft()
            cur += people[y][x]
            if x > 0:
                if dp[y][x-1] > cur:
                    dp[y][x-1] = cur
                    append((y, x-1, cur))
            if x < N-1:
                if dp[y][x+1] > cur:
                    dp[y][x+1] = cur
                    append((y, x+1, cur))
            if y > 0:
                if dp[y-1][x] > cur:
                    dp[y-1][x] = cur
                    append((y-1, x, cur))
            if y < N-1:
                if dp[y+1][x] > cur:
                    dp[y+1][x] = cur
                    append((y+1, x, cur))

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

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
    for p in P:
        p -= 1
        i = p // N
        j = p % N
        answer += dp[i][j]
        people[i][j] = False
        que = deque([(i, j, dp[i][j])])
        popleft = que.popleft; append = que.append
        while que:
            y, x, cur = popleft()
            cur += people[y][x]
            if x > 0:
                if dp[y][x-1] > cur:
                    dp[y][x-1] = cur
                    append((y, x-1, cur))
            if x < N-1:
                if dp[y][x+1] > cur:
                    dp[y][x+1] = cur
                    append((y, x+1, cur))
            if y > 0:
                if dp[y-1][x] > cur:
                    dp[y-1][x] = cur
                    append((y-1, x, cur))
            if y < N-1:
                if dp[y+1][x] > cur:
                    dp[y+1][x] = cur
                    append((y+1, x, cur))

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

Submission status: Time Limit Exceeded

Solution code:
from numba import jit

@jit
def main():
  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)

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

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
    for p in P:
        p -= 1
        i = p // N
        j = p % N
        answer += dp[i][j]
        people[i][j] = False
        que = deque([(i, j, dp[i][j])])
        popleft = que.popleft; append = que.append
        while que:
            y, x, cur = popleft()
            cur += people[y][x]
            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:
                        dp[ny][nx] = cur
                        append((ny, nx, cur))

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
Ps = list(map(int, input().split()))
Ps = [p-1 for p in Ps]
fs = [0] * (n**2)

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

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

print(ans)

Submission status: Time Limit Exceeded

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

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

    N = NI()
    P = LI()

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

    ans = 0

    for i in P:
        x = (i-1) % N
        y = (i-1) // N
        min_cnt = INF
        if x == 0 or x == N-1 or y == 0 or y == N-1:
            min_cnt = 0
        else:

            dp = [[INF] * N for _ in range(N)]
            d = 0
            f = 0
            q = collections.deque()
            q.append((f,d,x,y))
            dp[x][y] = 0
            while q:
                f,d,i,j = q.popleft()
                if d > min(x,N-x,y,N-y): break
                for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                    if not(0 <= i+di < N and 0 <= j+dj < N):
                        min_cnt = min(min_cnt,f)
                        continue
                    if zero[i+di][j+dj] == 0:
                        min_cnt = min(min_cnt,f)
                        continue
                    e = seat[i+di][j+dj]
                    if dp[i+di][j+dj] > f+e:
                        dp[i+di][j+dj] = f+e
                        q.append((f+e,d,i+di,j+dj))

        seat[x][y] = 0
        if min_cnt == 0:
            zero[x][y] = 0
        ans += min_cnt
    print(ans)

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

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)

    def bfs(sy, sx):
        que = deque([(sy, sx, dp[sy][sx])])
        popleft = que.popleft; append = que.append
        while que:
            y, x, cur = popleft()
            cur += people[y][x]
            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:
                        dp[ny][nx] = cur
                        append((ny, nx, cur))

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

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

Submission status: Time Limit Exceeded

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

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

    N = NI()
    P = LI()

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

    ans = 0

    for i in P:
        x = (i-1) % N
        y = (i-1) // N
        min_cnt = INF
        if x == 0 or x == N-1 or y == 0 or y == N-1:
            min_cnt = 0
        else:

            dp = [[INF] * N for _ in range(N)]
            d = 0
            f = 0
            q = []
            heapify(q)
            heappush(q,(f,d,x,y))
            dp[x][y] = 0
            while q:
                f,d,i,j = heappop(q)
                if d > min(x,N-x,y,N-y): break
                for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                    if not(0 <= i+di < N and 0 <= j+dj < N):
                        break
                    if zero[i+di][j+dj] == 0:
                        break
                    e = seat[i+di][j+dj]
                    if dp[i+di][j+dj] > f+e:
                        dp[i+di][j+dj] = f+e
                        heappush(q,(f+e,d,i+di,j+dj))
                else:
                    continue
                break
            min_cnt = f

        seat[x][y] = 0
        if min_cnt == 0:
            zero[x][y] = 0
        ans += min_cnt
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
Ps = list(map(int, input().split()))
Ps = [p-1 for p in Ps]
fs = [0] * (n**2)

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

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
Ps = list(map(int, input().split()))
fs = [0] * (n**2)

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

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
Ps = list(map(int, input().split()))
fs = [0] * (n**2)

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

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

Submission status: Time Limit Exceeded

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

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

    N = NI()
    P = LI()

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

    ans = 0

    for i in P:
        x = (i-1) % N
        y = (i-1) // N
        min_cnt = INF
        if x == 0 or x == N-1 or y == 0 or y == N-1:
            min_cnt = 0
        else:

            dp = [[INF] * N for _ in range(N)]
            d = 0
            q = []
            heapify(q)
            heappush(q,(d,x,y))
            dp[x][y] = 0
            while q:
                d,i,j = heappop(q)
                for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
                    if not(0 <= i+di < N and 0 <= j+dj < N):
                        break
                    if zero[i+di][j+dj] == 0:
                        break
                    e = seat[i+di][j+dj]
                    if dp[i+di][j+dj] > d+e:
                        dp[i+di][j+dj] = d+e
                        heappush(q,(d+e,i+di,j+dj))
                else:
                    continue
                min_cnt = d
                break

        seat[x][y] = 0
        if min_cnt == 0:
            # q = collections.deque()
            # q.append((x,y))
            zero[x][y] = 0
            # while q:
            #     i,j = q.popleft()
            #     for di,dj in ((1,0),(0,1),(-1,0),(0,-1)):
            #         if not(0 <= i+di < N and 0 <= j+dj < N): continue
            #         if seat[i+di][j+dj] == 1 or zero[i+di][j+dj] == 0: continue
            #         zero[i+di][j+dj] = 0
            #         q.append((i+di,j+dj))
        ans += min_cnt
    print(ans)

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 toP(h,w):
    return h * n + w

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

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