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:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import functools
import heapq
import itertools
import logging
import math
import os
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from io import BytesIO, IOBase
from typing import Dict, List, Optional, Set, Tuple

sys.setrecursionlimit(pow(2, 31) - 1)

UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3


def solve(values: List[int], nb: int) -> int:
    # min nb of neighbours from here to exit
    grid = [[min(i, nb - i - 1, j, nb - j - 1) for j in range(nb)] for i in range(nb)]
    answer = 0
    still_inside = [[True] * nb for _ in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    for v in values:
        i, j = divmod(v - 1, nb)
        answer += grid[i][j]
        # LOG.debug((i, j, grid[i][j]))
        still_inside[i][j] = 0
        dfs(nb, grid, i, j, still_inside)
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def dfs(nb: int, grid: List[List[int]], i: int, j: int, still_inside: List[List[bool]]):
    neighbours = set(
        (next_i, next_j)
        for next_i, next_j in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
        if 0 <= next_i < nb and 0 <= next_j < nb
    )
    new_score = min(
        still_inside[next_i][next_j] + grid[next_i][next_j]
        for next_i, next_j in neighbours
    )
    if new_score < grid[i][j]:
        grid[i][j] = new_score
    for next_i, next_j in neighbours:
        if grid[next_i][next_j] > grid[i][j] + still_inside[i][j]:
            dfs(nb, grid, next_i, next_j, still_inside)
            grid[next_i][next_j] = grid[i][j] + still_inside[i][j]


def update_neighbours(nb: int, grid: List[List[int]], i: int, j: int):
    # update neighbours
    if j < nb - 1:
        grid[i][j][RIGHT] = grid[i][j + 1][RIGHT]
    if j > 0:
        grid[i][j][LEFT] = grid[i][j - 1][LEFT]
    if i < nb - 1:
        grid[i][j][UP] = grid[i + 1][j][UP]
    if i > 0:
        grid[i][j][DOWN] = grid[i - 1][j][DOWN]
    for left in range(j):
        grid[i][left][RIGHT] = max(0, grid[i][left][RIGHT])
    for right in range(j + 1, nb):
        grid[i][right][LEFT] = max(0, grid[i][right][LEFT])
    for up in range(i):
        grid[up][j][DOWN] = max(0, grid[up][j][DOWN])
    for down in range(i + 1, nb):
        grid[down][j][UP] = max(0, grid[down][j][UP])


def do_job(stdin, stdout):
    "Do the work"
    LOG.debug("Start working")
    # first line is number of test cases
    N = int(stdin.readline().strip())
    values = list(map(int, stdin.readline().split()))
    # values = []
    # for _ in range(N):
    #     values.append(stdin.readline().split())
    result = solve(values, N)
    print(result, file=stdout)


def print_output(testcase: int, result, stdout) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result), file=stdout)
    # 6 digits float precision {:.6f} (6 is the default value)
    # print("Case #{}: {:f}".format(testcase + 1, result), file=stdout)


BUFSIZE = 8192


class FastIO(IOBase):
    # pylint: disable=super-init-not-called, expression-not-assigned
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    # pylint: disable=super-init-not-called
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def configure_log() -> None:
    "Configure the log output"
    log_formatter = logging.Formatter("L%(lineno)d - " "%(message)s")
    handler = logging.StreamHandler(IOWrapper(sys.stderr))
    handler.setFormatter(log_formatter)
    LOG.addHandler(handler)


LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
    LOG = logging.getLogger("template")
    configure_log()


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="run as verbose mode",
    )
    args = parser.parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)
    stdin = IOWrapper(sys.stdin)
    stdout = IOWrapper(sys.stdout)
    do_job(stdin, stdout)
    stdout.flush()
    for h in LOG.handlers:
        h.flush()
    return 0


if __name__ == "__main__":
    sys.exit(main())

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[j+1]=S.index(j+1)
for i in range(N*N):
  player=S[i]
  hayasa=P[player]
  
  que=[[] for _ in range(N)]
  d=[-1]*(N*N+1)
  que[0].append(player)
  d[player]=0
  
  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]==-1:
        if P[kouho+N]>hayasa:
          que[j+1].append(kouho+N)
          d[kouho+N]=0
        else:
          que[j].append(kouho+N)
          d[kouho+N]=0
          
      if d[kouho-N]==-1:
        if P[kouho-N]>hayasa:
          que[j+1].append(kouho-N)
          d[kouho-N]=0
        else:
          que[j].append(kouho-N)
          d[kouho-N]=0
          
      if d[kouho+1]==-1:
        if P[kouho+1]>hayasa:
          que[j+1].append(kouho+1)
          d[kouho+1]=0
        else:
          que[j].append(kouho+1)
          d[kouho+1]=0
          
      if d[kouho-1]==-1:
        if P[kouho-1]>hayasa:
          que[j+1].append(kouho-1)
          d[kouho-1]=0
        else:
          que[j].append(kouho-1)
          d[kouho-1]=0
    if finish==1:
      count+=j
      break
    j+=1    
print(count)

Submission status: Time Limit Exceeded

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

space = [1]*(n*n)

dist = [0]*(n*n)
for r in range(n):
    for c in range(n):
        dist[r*n+c] = min(r, (n-1)-r, c, (n-1)-c)

ans = 0
for pi in p:
    pi -= 1
    q = [pi]
    ans += dist[pi]
    space[pi] = 0

    while q:
        pp = q.pop()
        for dxi in [-n,-1,1,n]:
            if dxi == 1 and pp % n==n-1: continue
            if dxi == -1 and pp % n ==n: continue
            if 0<=pp+dxi<n*n and dist[pp+dxi] > dist[pp]+space[pp]:
                q.append(pp+dxi)
                dist[pp+dxi] = dist[pp]+space[pp]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

import sys
readline = sys.stdin.readline
read = sys.stdin.read

n,*p = map(int,read().split())
N = n*n

dist = [0]*N

for a in range(n):
    for b in range(n):
        dist[a*n+b] = min(a,n-1-a,b,n-1-b)

#print(dist)


#ans = [0]*N
ans = 0
iru = [1]*N

for pi in p:
    pi -= 1

    ans += dist[pi]
    iru[pi] = 0

    q = [pi]
    #更新
    
    while q:
        #print(q)
        v = q.pop()
        for i in [-n,-1,1,n]:
            if i==1 and v%n==n-1: continue
            if i==-1 and v%n==0: continue
            nv = v+i
            if 0 <= nv < N and dist[nv] > dist[v] + iru[v]:
                q.append(nv)
                dist[nv] = dist[v] + iru[v]
        
                    
    #print(dist)        

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush

import numpy as np

from numba import njit


# def pg(aaa):
#     for i in range(0, n2 ** 2, n2):
#         print(aaa[i:i + n2])
#     print()

@njit
def prepare_seats(n):
    n2 = n + 2
    seats = [-1] * (n2 * n2)
    is_seated = [False] * (n2 * n2)
    for i in range(n):
        ud = min(i, n - 1 - i)
        for j in range(n):
            ij = (i + 1) * n2 + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = True
    return seats, is_seated


@njit
def bfs(n2, s, seats, is_seated):
    MOVE = (-n2, -1, 1, n2)

    q = [s]
    updated = set()

    while q:
        val, j = heappop(q)
        if j in updated:
            continue
        updated.add(j)
        seats[j] = val
        if is_seated[j]:
            val += 1
        for dj in MOVE:
            nj = j + dj
            if seats[nj] > val and nj not in updated:
                heappush(q, (val, nj))


@njit
def solve(n, ppp):
    n2 = n + 2
    seats, is_seated = prepare_seats(n)

    ans = 0

    for p in ppp:
        i, j = divmod(p - 1, n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = False
        bfs(n2, (res, i), seats, is_seated)

    print(ans)


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int32)
solve(n, ppp)

Submission status: Time Limit Exceeded

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

space = [1]*(n*n)

dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

dist = [0]*(n*n)
for r in range(n):
    for c in range(n):
        dist[r*n+c] = min(r, (n-1)-r, c, (n-1)-c)

ans = 0
for pi in p:
    row, col = divmod(pi-1, n)
    q = [(row, col)]
    ans += dist[pi-1]
    space[row*n + col] = 0

    while q:
        ph, pw = q.pop()
        for dyi, dxi in zip(dy,dx):
            if 0<=ph+dyi<n and 0<=pw+dxi<n:
                if dist[(ph+dyi)*n+(pw+dxi)] > dist[ph*n+pw]+space[(ph)*n+(pw)]:
                    q.append((ph+dyi,pw+dxi))
                    dist[(ph+dyi)*n+(pw+dxi)] = dist[ph*n+pw]+space[(ph)*n+(pw)]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from heapq import heappop, heappush

import numpy as np

from numba import njit


# def pg(aaa):
#     for i in range(0, n2 ** 2, n2):
#         print(aaa[i:i + n2])
#     print()

@njit
def solve(n, ppp):
    n2 = n + 2
    row_base = [0] * n
    for i in range(n):
        row_base[i] = min(i, n - 1 - i)

    seats = [-1] * (n2 * n2)
    is_seated = [False] * (n2 * n2)
    for i in range(n):
        ud = min(i, n - 1 - i)
        for j in range(n):
            ij = (i + 1) * n2 + j + 1
            seats[ij] = min(ud, row_base[j])
            is_seated[ij] = True

    ans = 0
    MOVE = (-n2, -1, 1, n2)

    for p in ppp:
        i, j = divmod(p - 1, n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = False

        q = [(res, i)]
        updated = set()

        while q:
            val, j = heappop(q)
            if j in updated:
                continue
            updated.add(j)
            seats[j] = val
            if is_seated[j]:
                val += 1
            for dj in MOVE:
                nj = j + dj
                if seats[nj] > val and nj not in updated:
                    heappush(q, (val, nj))
        # print(p, i, res)
        # pg(seats)

    print(ans)


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int32)
solve(n, ppp)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import deque

N=int(input())
b=[[0]*N for _ in range(N)]
c=[[1]*N for _ in range(N)]

q = deque()

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

def decb(q, hito):
    x = hito % N
    y = hito // N

    v=9999
    if y>0: v=b[y-1][x]+c[y-1][x]
    else: v=0
    if y<N-1: v=min(v, b[y+1][x]+c[y+1][x])
    else: v=0
    if x>0: v=min(v, b[y][x-1]+c[y][x-1])
    else: v=0
    if x<N-1: v=min(v, b[y][x+1]+c[y][x+1])
    else: v=0

    b[y][x]=v

    if x>0 and b[y][x-1] > v: q.append(hito-1)
    if x<N-1 and b[y][x+1] > v: q.append(hito+1)
    if y>0 and b[y-1][x] > v: q.append(hito-N)
    if y<N-1 and b[y+1][x] > v: q.append(hito+N)

def unsetb(hito):
    global N, b
    x = hito % N
    y = hito // N
    c[y][x]=0
    ret = b[y][x]
    q.append(hito)

    while len(q)>0:
        decb(q, q.pop())
    return ret

def main():
    global b
    A=list(map(int, input().split()))
    ans=0
    for hito in A:
        ans+=unsetb(hito-1)
    print(ans)

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(-1, n + 1):
            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]
            for my, mx in m:
                myx = my * n + mx + yx
                my, mx = d[myx]
                if 0 < my < n - 1 and 0 < mx < n - 1:
                    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:
import sys
from collections import deque

n, *ppp = map(int, sys.stdin.buffer.read().split())

n2 = n + 2
row_base0 = list(range(n))
row_base1 = [-1] + row_base0 + [-1]
row_base0.reverse()
row_base2 = [-1] + row_base0 + [-1]
row_base = [min(a, b) for a, b in zip(row_base1, row_base2)]

seats = [-1] * n2
for i in range(n):
    ud = min(i, n - 1 - i)
    seats.extend(min(a, ud) for a in row_base)
seats.extend([-1] * n2)

is_seated = [False] * n2
is_seated.extend(([False] + [True] * n + [False]) * n)
is_seated.extend([False] * n2)


def pg(aaa):
    for i in range(0, n2 ** 2, n2):
        print(aaa[i:i + n2])
    print()


ans = 0
MOVE = (-n2, -1, 1, n2)
q = deque()
popl = q.popleft
appl = q.appendleft
appr = q.append
clrq = q.clear

for p in ppp:
    i, j = divmod(p - 1, n)
    i = (i + 1) * n2 + j + 1
    res = seats[i]
    ans += res
    is_seated[i] = False

    appr((res, i))
    updated = set()

    while q:
        val, j = popl()
        if j in updated:
            continue
        updated.add(j)
        seats[j] = val
        if is_seated[j]:
            val += 1
            upd_func = appr
        else:
            upd_func = appl
        for dj in MOVE:
            nj = j + dj
            if seats[nj] > val and nj not in updated:
                upd_func((val, nj))
    clrq()
    # print(p, i, res)
    # pg(seats)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
p = LI()
p = [((i-1)%n, (i-1)//n) for i in p]
ans = 0
dp = [[min(i, j, n - (i + 1), n - (j + 1)) for j in range(n)] for i in range(n)]
dp2 = [[False]*n for _ in range(n)]
dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]
for (q, r) in p:
    ans += dp[r][q]
    dp2[r][q] = True
    h = [(dp[r][q], r, q)]
    while h:
        d, y, x = h.pop()
        if not dp2[y][x]:
            d += 1
        for j in range(4):
            ny, nx = y + dy[j], x + dx[j]
            if 0 <= ny < n and 0 <= nx < n:
                if dp[ny][nx] > d:
                    dp[ny][nx] = d
                    h.append((d, ny, nx))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
P = ([int(c)-1 for c in input().split()])


def proc(N, P):
    ans = 0
    Removed = [[0]*N for _ in range(N)]
    Mat = [[0]*N for _ in range(N)]
    Dy, Dx = [1,0,-1,0], [0,1,0,-1]

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

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    import time
    from collections import deque
    input = sys.stdin.readline
    sys.setrecursionlimit(10**6)
    N = int(input())
    P = [int(a) for a in input().strip().split()]
    G = [[min(n, N-n-1,i, N-i-1) for i in range(N)] for n in range(N)]
    Gflag = [[1] * N for _ in range(N)]
    ans = 0

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

    for p in P:
        row, col = (p-1) // N, (p-1) % N
        ans += G[row][col]
        Gflag[row][col] = 0
        q = deque([(G[row][col], row, col)])
        while q:
            cost, row, col = q.popleft()
            if row > 0:
                if G[row-1][col] > cost + Gflag[row][col]:
                    G[row-1][col] = cost + Gflag[row][col]
                    q.append((cost+Gflag[row][col], row-1, col))
            if row < N-1:
                if G[row+1][col] > cost + Gflag[row][col]:
                    G[row+1][col] = cost + Gflag[row][col]
                    q.append((cost+Gflag[row][col], row+1, col))
            if col > 0:
                if G[row][col-1] > cost + Gflag[row][col]:
                    G[row][col-1] = cost + Gflag[row][col]
                    q.append((cost+Gflag[row][col], row, col-1))
            if col < N-1:
                if G[row][col+1] > cost + Gflag[row][col]:
                    G[row][col+1] = cost + Gflag[row][col]
                    q.append((cost+Gflag[row][col], row, col+1))

    print(ans)
    
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)
    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]
            for my, mx in m:
                myx = my * n + mx + yx
                if d[myx]:
                    my, mx = d[myx]
                else:
                    my, mx = divmod(myx, n)
                    d[myx] = (my, mx)
                if 0 < my < n - 1 and 0 < mx < n - 1:
                    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:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
p = LI()
p = [((i-1)%n, (i-1)//n) for i in p]
ans = 0
dp = [[min(i, j, n - (i + 1), n - (j + 1)) for j in range(n)] for i in range(n)]
dp2 = [[False]*n for _ in range(n)]
for (q, r) in p:
    ans += dp[r][q]
    dp2[r][q] = True
    h = [(dp[r][q], r, q)]
    while h:
        d, y, x = heappop(h)
        if not dp2[y][x]:
            d += 1
        if x != 0:
            if dp[y][x-1] > d:
                dp[y][x-1] = d
                heappush(h, (d, y, x-1))
        if x != n-1:
            if dp[y][x+1] > d:
                dp[y][x+1] = d
                heappush(h, (d, y, x+1))
        if y != 0:
            if dp[y-1][x] > d:
                dp[y-1][x] = d
                heappush(h, (d, y-1, x))
        if y != n-1:
            if dp[y+1][x] > d:
                dp[y+1][x] = d
                heappush(h, (d, y+1, x))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
p = LI()
p = [((i-1)%n, (i-1)//n) for i in p]
ans = 0
dp = [[min(i, j, n - (i + 1), n - (j + 1)) for j in range(n)] for i in range(n)]
dp2 = [[False]*n for _ in range(n)]
dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]
for (q, r) in p:
    ans += dp[r][q]
    dp2[r][q] = True
    h = [(dp[r][q], r, q)]
    while h:
        d, y, x = heappop(h)
        if not dp2[y][x]:
            d += 1
        for j in range(4):
            ny, nx = y + dy[j], x + dx[j]
            if 0 <= ny < n and 0 <= nx < n:
                if dp[ny][nx] > d:
                    dp[ny][nx] = d
                    heappush(h, (d, ny, nx))
print(ans)

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)]
    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]
            for my, mx in m:
                myx = my * n + mx + yx
                if 0 < myx // n < n - 1 and 0 < myx % n < n - 1:
                    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:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
p = LI()

ans = 0
dp = [[min(i, j, n - (i + 1), n - (j + 1)) for j in range(n)] for i in range(n)]
dp2 = [[False]*n for _ in range(n)]
dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]
for i in p:
    q = (i-1) % n
    r = (i-1) // n
    ans += dp[r][q]
    dp2[r][q] = True
    h = []
    heappush(h, (dp[r][q], r, q))
    while h:
        d, y, x = heappop(h)
        if not dp2[y][x]:
            d += 1
        for j in range(4):
            ny, nx = y + dy[j], x + dx[j]
            if 0 <= ny < n and 0 <= nx < n:
                if dp[ny][nx] > d:
                    dp[ny][nx] = d
                    heappush(h, (d, ny, nx))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    from collections import deque
    from copy import deepcopy
    #input = sys.stdin.readline
    n = int(input())
    p = [int(i)-1 for i in input().split()]
    c = [[1]*n for _ in range(n)] 
    d = [[0]*n for _ in range(n)] 
    for x in range(n):
        for y in range(n):
            d[y][x] += min(x, n-x-1, y, n-y-1)
    ans = 0
    for i in p:
        x, y = i%n, i//n
        c[y][x] = 0
        ans += d[y][x]
        que = deque([[x, y]])
        while que:
            x, y = que.popleft()
            for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
                nx, ny = x+dx, y+dy
                if 1<=nx<n-1 and 1<=ny<n-1:
                    if d[y][x]+c[y][x]<d[ny][nx]:
                        d[ny][nx] = d[y][x]+c[y][x]
                        que.append([nx, ny])
    return print(ans)
    
if __name__ == '__main__':
    main()