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:
from collections import deque
import copy
n = int(input())
order = tuple(map(lambda x:int(x)-1, input().split()))

def bfs(i_y, i_x):
    tmp_chairs = copy.deepcopy(chairs)
    queue = deque()
    start = (i_y, i_x, 0)
    queue.append(start)
    # res = []
    res = 600
    while queue:
        y, x, unlike = queue.popleft()
        flag = False
        for i in range(4):
            tmp_y = y + dy[i]
            tmp_x = x + dx[i]
            if tmp_x >= n or tmp_x < 0 or tmp_y >= n or tmp_y < 0:
                chairs[i_y][i_x] = -1
                res = min(res, unlike)
                # res.append(unlike)
                flag = True
                # return unlike
            elif tmp_chairs[tmp_y][tmp_x] == -1:
                tmp_chairs[y][x] = -2
                queue.append((tmp_y, tmp_x, unlike))
                flag = True
            else:
                if tmp_chairs[tmp_y][tmp_x] != -2:
                    if tmp_y >= n-((n//2)-1) or tmp_y < (n//2)-1 or tmp_x >= n-((n//2)-1) or tmp_x < (n//2)-1:
                        tmp_chairs[y][x] = -2
                        queue.append((tmp_y, tmp_x, unlike+1))
                        flag = True
        if not flag:
            for i in range(4):
                tmp_y = y + dy[i]
                tmp_x = x + dx[i]
                if tmp_chairs[tmp_y][tmp_x] != -2: 
                    tmp_chairs[y][x] = -2
                    queue.append((tmp_y, tmp_x, unlike+1))
    # return min(res)
    return res
# 座席作成
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
ans = 0
chairs = [[0] * n for _ in range(n)]
for i in range(n):
    for i_, j in enumerate(range(i*n, i*n+n)):
        chairs[i][i_] = j

for num in order:
    cnt = 0
    i_y, i_x = num//n, num%n
    ans += bfs(i_y, i_x)
print(ans)

Submission status: Wrong Answer

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:
    # nb of neighbours from here to exit from up, down, left, right
    grid = [[[i, nb - i - 1, j, nb - j - 1] for j in range(nb)] for i in range(nb)]
    # LOG.debug(("\n".join(map(str, grid))))
    answer = 0
    for v in values:
        i, j = divmod(v - 1, nb)
        # result = dfs(nb, grid, i, j, set())
        result = min(grid[i][j])
        # LOG.debug((i, j, result))
        answer += result
        # 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] -= 1
            if grid[i][left][RIGHT] < 0:
                grid[i][left][RIGHT] = 0
        for right in range(j + 1, nb):
            grid[i][right][LEFT] -= 1
            if grid[i][right][LEFT] < 0:
                grid[i][right][LEFT] = 0
        for up in range(i):
            grid[up][j][DOWN] -= 1
            if grid[up][j][DOWN] < 0:
                grid[up][j][DOWN] = 0
        for down in range(i + 1, nb):
            grid[down][j][UP] -= 1
            if grid[down][j][UP] < 0:
                grid[down][j][UP] = 0
        # LOG.debug(("\n".join(map(str, grid))))
    return answer


def dfs(
    nb: int, grid: List[List[int]], i: int, j: int, visited: Set[Tuple[int, int]]
) -> int:
    if i <= 0 or i >= nb - 1 or j <= 0 or j >= nb - 1:
        return 0
    if min(grid[i][j]) == 0:
        return 0
    visited.add((i, j))
    return 1 + min(
        dfs(nb, grid, *neighbour, visited)
        for neighbour in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
        if neighbour not in visited
    )


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

Solution code:
INF = float("inf")
n = int(input())
P = list(map(int, input().split()))
T = [[INF] * (n+2) for _ in range(n+2)]
rest = [[1] * (n+2) for _ in range(n+2)]
ans = 0
for i in range(n+2):
    if i == 0 or i == n+1:
        for j in range(n+2):
            rest[i][j] = INF
    else:
        rest[i][0] = INF
        rest[i][n+1] = INF
        T[1][i] = 1
        T[n][i] = 1
        T[i][1] = 1
        T[n][1] = 1
def check(i,j):
    mn = min(T[i-1][j], T[i][j-1], T[i][j+1], T[i+1][j])
    tmp = mn + rest[i][j]
    if tmp < T[i][j]:
        T[i][j] = tmp

for p in P:
    s = (p-1) // n + 1
    t = (p-1) % n + 1
    rest[s][t] = 0
    if s in (1,n) or t in (1,n):
        T[s][t] = 0
        continue

    for i in range(2, n):
        for j in range(2, n):
            check(i, j)
            check(i, n-j+1)
            check(n-i+1, j)
            check(n-i+1, n-j+1)

    ans += T[s][t]
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
import math
N=int(input())
List=list(map(int, input().split()))
MAS=np.arange(1,N**2+1)
print(MAS)
MAS=MAS.reshape(N,N)
print(MAS)

i=0
ans=0
while i<N**2:
    if List[i]<=N:
        pass
    elif List[i]>=((N**2)-(N-1)):
        pass
    elif (List[i]-1)%N==0 or List[i]%N==0:
        pass
    else:
        ans+=1
    i+=1
    
if N>3:
    Maina=0
    n=1
    while n<=N-3:
        #print("A")
        Maina+=n
        n+=1
    print(ans-Maina)
    quit()
    

print(ans)

Submission status: Wrong Answer

Solution code:
class UnionFind:
    __slots__ = ["_size", "_first_idx", "_parents", "_cost"]

    def __init__(self, size: int, N: int, first_index: int = 0) -> None:
        self._size = size
        self._first_idx = first_index
        self._parents = [-1] * (size + first_index)

        cost = [0] * (N * N)
        for r in range(N):
            dr = min(r, N - 1 - r)
            for c in range(N):
                dc = min(c, N - 1 - c)
                cost[r * N + c] = min(dr, dc)
        self._cost = cost

    def find(self, x: int) -> int:
        """Find the group (root) of vertex x"""
        if self._parents[x] < 0:
            return x
        self._parents[x] = self.find(self._parents[x])
        return self._parents[x]

    def is_same(self, x: int, y: int) -> bool:
        """Return whether two vertices x and y are in the same group or not."""
        return self.find(x) == self.find(y)

    def unite(self, x: int, y: int) -> None:
        """Unite two groups of vertices x and y."""
        c = min(self._cost[x], self._cost[y])
        x, y = self.find(x), self.find(y)
        if x == y:
            self._cost[x] = min(self._cost[x], c)
            return

        if self._parents[x] > self._parents[y]:
            x, y = y, x
        self._parents[x] += self._parents[y]
        self._parents[y] = x
        self._cost[x] = min(self._cost[x], c)

    def get_size(self, x: int) -> int:
        """Get the size of the group vertex x belongs"""
        return -self._parents[self.find(x)]

    def get_cost(self, x: int) -> int:
        x = self.find(x)
        return self._cost[x]

    def set_cost(self, x: int, val: int):
        x = self.find(x)
        self._cost[x] = min(self._cost[x], val)


def main():
    N = int(input())
    *p, = (int(x) - 1 for x in input().split())

    g = [[set() for _ in range(N)] for _ in range(N)]
    for r in range(N):
        for c in range(N):
            if r > 0:
                g[r][c].add((r - 1, c))
            if c > 0:
                g[r][c].add((r, c - 1))
            if r < N - 1:
                g[r][c].add((r + 1, c))
            if c < N - 1:
                g[r][c].add((r, c + 1))

    uf = UnionFind(N * N, N)

    ex = [[0] * N for _ in range(N)]

    ans = 0
    for pi in p:
        r, c = divmod(pi, N)

        t = uf.get_cost(pi)
        for nr, nc in g[r][c]:
            if uf.is_same(nr * N + nc, pi):
                continue
            else:
                t = min(t, uf.get_cost(nr * N + nc) + (0 if ex[nr][nc] else 1))
        ans += t

        # uf._cost[pi] = min(uf._cost[pi], t)
        ex[r][c] = 1
        for nr, nc in g[r][c]:
            if ex[nr][nc]:
                uf.unite(nr * N + nc, pi)

    print(ans)


if __name__ == '__main__':
    main()

# import sys
# input = sys.stdin.readline
#
# sys.setrecursionlimit(10 ** 7)
#
# (int(x)-1 for x in input().split())
# rstrip()
#
# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok

Submission status: Wrong Answer

Solution code:


def DFS(m,n,x,y,f,th):
    # print(x,y,th)
    if x in(0,n-1) or y in(0,n-1) or th >= min(n-x,n-y):
        return th

    r = (x+1)%n
    l = (x-1)%n
    t = (y+1)%n
    b = (y+1)%n
    flg = 999999999999
    if m[y][r] == 0 and f != 'l':
        flg = min(DFS(m,n,r,y,'r',th),flg)
    elif m[y][r] == 1 and f != 'l':
        flg = min(flg,DFS(m,n,r,y,'r',th+1))
    if m[y][l] == 0  and f != 'r':
        flg = min(flg,DFS (m,n,l,y,'l',th))
    elif m[y][l] == 1  and f != 'r':
        flg = min(flg,DFS (m,n,l,y,'l',th+1))
    if m[t][x] == 0 and f != 'b':
        flg = min(flg,DFS(m,n,x,t,'b',th))
    elif m[t][x] == 1 and f != 'b':
        flg = min(flg,DFS(m,n,x,t,'b',th+1))
    if m[b][x] == 0 and f != 't': 
        flg = min(flg,DFS(m,n,x,b,'t',th))
    elif m[b][x] == 1 and f != 't':
        flg = min(DFS(m,n,x,b,'t',th+1),flg)
    return flg



n = int(input())
p = [int(i)-1 for i in input().split()]
# print(p)


m = [[1] * n for i in range(n)]
# print(m)
c = 0
for i in p:
    x = i%n
    y = -(-(i+1)//n)-1 
    m[y][x] = 0
    c += (DFS(m,n,x,y,'',0))
    # print('aa',i+1,c)
        
    
print(c)

Submission status: Wrong Answer

Solution code:
input()
print(1)

Submission status: Wrong Answer

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 i in range(N):
    a = i//n
    b = i%n
    dist[i] = min(a,n-1-a,b,n-1-b)

#print(dist)


#ans = [0]*N
ans = 0
iru = [1]*N
for I,pi in enumerate(p):
    pi -= 1

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
N = int(input())
# = map(int, input().split())
P = list(map(int, input().split()))
# = [int(input()) for i in range(N)]
# = [list(map(int, input().split())) for i in range(N)]
seat = np.ones((N, N))
total = 0

for i in range(N**2):
    tate = (P[i]-1)//N
    yoko = (P[i]-1)%N
    if yoko == 0 or yoko == N-1 or tate == 0:
        seat[tate][yoko] = 0
    else:
        shortest = N
        count = 0
        for i in range(yoko):
            if seat[tate][i] == 1:
                count+=1
        if count < shortest:
            shortest = count
        count = 0
        for i in range(N-yoko):
            if seat[tate][N-1-i] == 1:
                count += 1
        if count < shortest:
            shortest = count
#        count = 0
#        for i in range(tate):
#            if seat[i][yoko] == 1:
#                count+=1
#        if count < shortest:
#            shortest = count
#        count = 0
#        for i in range(N-tate):
#            if seat[N-1-i][yoko] == 1:
#                count += 1
#        if count < shortest:
#            shortest = count
        total += shortest
        seat[tate][yoko] = 0

print(total)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 9)

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

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

def _f(i, j):
    for d in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
        ii, jj = i + d[0], j + d[1]
        if 0 <= ii < n and 0 <= jj < n:
            if m[ii][jj] > m[i][j]:
                _f(ii, jj)
                m[ii][jj] = m[ii][jj] - 1

res = 0
for p in pp:
    i, j = (p-1) // n, (p-1) % n
    s = m[i][j]
    res = res + max(0, s)
    _f(i, j)
    if s > 0:
        m[i][j] = 0.5

print(res)

Submission status: Wrong Answer

Solution code:
import sys
#import numpy as np
#import math
#from fractions import Fraction
#import itertools
from collections import deque
#import heapq
from fractions  import gcd

input=sys.stdin.readline

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

inf = 0
num_min =2**(n-1).bit_length()
dat1=[inf]*(2*num_min-1)
dat2=[inf]*(2*num_min-1)

#初期化
for i in range(n):
    dat1[i+num_min-1]=1
    dat2[i+num_min-1]=1
for i in range(num_min-2,-1,-1):
    dat1[i]=dat1[2*i+1]+dat1[2*i+2]
    dat2[i]=dat2[2*i+1]+dat2[2*i+2]
#親のノード(n-1)//2
#子のノード2n+1,2n+2

def segfunc(x,y):
    return x+y

def update1(i,x):
    i+=num_min-1
    dat1[i]=x
    while i>0:
        i=(i-1)//2
        dat1[i]=segfunc(dat1[2*i+1],dat1[2*i+2])

def update2(i,x):
    i+=num_min-1
    dat2[i]=x
    while i>0:
        i=(i-1)//2
        dat2[i]=segfunc(dat2[2*i+1],dat2[2*i+2])

def query1(a,b): #半開区間、[a,b)の最小値
    if b<=a:
        return inf
    res1=inf
    a += num_min-1
    b += num_min-2
    while b-a>1:
        if a&1==0:
            res1 = segfunc(res1,dat1[a])
        if b&1==1:
            res1 = segfunc(res1,dat1[b])
        a=a//2
        b=(b-1)//2
    if a==b:
        res1 = segfunc(res1,dat1[a])
    else:
        res1=segfunc(segfunc(res1,dat1[a]),dat1[b])
    return res1
def query2(a,b): #半開区間、[a,b)の最小値
    if b<=a:
        return inf
    res2=inf
    a += num_min-1
    b += num_min-2
    while b-a>1:
        if a&1==0:
            res2 = segfunc(res2,dat2[a])
        if b&1==1:
            res2 = segfunc(res2,dat2[b])
        a=a//2
        b=(b-1)//2
    if a==b:
        res2 = segfunc(res2,dat2[a])
    else:
        res2=segfunc(segfunc(res2,dat2[a]),dat2[b])
    return res2

ans=0
for k in p:
    i=k//m
    j=k%m
    
    if j==0:
        j=m
        i=i-1
    l=(j-1)*m+i+1
    res1=min(query1(i*m,k-1),query1(k,(i+1)*m))
    update1(k-1,0)
    res2=min(query2((j-1)*m,l-1),query2(l,j*m))
    r=min(res1,res2)
    ans+=r
    update2(l-1,0)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
P = list(map(int, input().split()))
T = [1] * (N*N)

m = 0
for i in range(len(P)):
    hate = 0
    T[P[i]-1] = 0
    if P[i] % N == 0 or P[i] % N == 1:
        hate = 0
    else:
        now = P[i]
        tate_up = now//N
        tate_down = N-now//N-1
        tate = min(tate_up, tate_down)
        yoko_r = (now//N+1)*N-now
        yoko_l = now-(now//N)*N+1
        yoko = min(yoko_r, yoko_l)

        if tate_up < tate_down:
            for j in range(tate):
                if T[now-N*j-1] == 1:
                    hate += 1
        else:
            for j in range(tate):
                if T[now+N*j-1] == 1:
                    hate += 1
        if yoko_r < yoko_l:
            for k in range(yoko):
                if T[now+k] == 1:
                    hate += 1
        else:
            for k in range(yoko):
                if T[now-k] == 1:
                    hate += 1
    if hate > m:
        m = hate
print(m)

Submission status: Wrong Answer

Solution code:
from collections import deque
import copy
n = int(input())
order = tuple(map(lambda x:int(x)-1, input().split()))

def bfs(i_y, i_x):
    tmp_chairs = copy.deepcopy(chairs)
    queue = deque()
    start = (i_y, i_x, 0)
    queue.append(start)
    res = []
    while queue:
        y, x, unlike = queue.popleft()
        flag = False
        for i in range(4):
            tmp_y = y + dy[i]
            tmp_x = x + dx[i]
            if tmp_x >= n or tmp_x < 0 or tmp_y >= n or tmp_y < 0:
                chairs[i_y][i_x] = -1
                res.append(unlike)
                flag = True
                # return unlike
            elif tmp_chairs[tmp_y][tmp_x] == -1:
                tmp_chairs[y][x] = -2
                queue.append((tmp_y, tmp_x, unlike))
                flag = True
            else:
                if tmp_chairs[tmp_y][tmp_x] != -2:
                    if tmp_y >= n-((n//2)-1) or tmp_y < (n//2)-1 or tmp_x >= n-((n//2)-1) or tmp_x < (n//2)-1:
                        tmp_chairs[y][x] = -2
                        queue.append((tmp_y, tmp_x, unlike+1))
                        flag = True
        if not flag:
            for i in range(4):
                tmp_y = y + dy[i]
                tmp_x = x + dx[i]
                if tmp_chairs[tmp_y][tmp_x] != -2: 
                    tmp_chairs[y][x] = -2
                    queue.append((tmp_y, tmp_x, unlike+1))
    return min(res)
# 座席作成
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
ans = 0
chairs = [[0] * n for _ in range(n)]
for i in range(n):
    for i_, j in enumerate(range(i*n, i*n+n)):
        chairs[i][i_] = j

for num in order:
    cnt = 0
    i_y, i_x = num//n, num%n
    ans += bfs(i_y, i_x)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
p = [int(i)-1 for i in input().split()]
c = [[1]*n for _ in range(n)] 
d = [[1]*n for _ in range(n)]
for x in range(n):
    for y in range(n):
        d[y][x] += min(min(x, n-x-1), min(y, n-y-1))
ans = 0
for i in p:
    x, y = i%n, i//n
    c[y][x] = 0
    ans += d[y][x]-1
    d[y][x] -= 1
    que = deque([[x, y]])
    while que:
        x, y = que.popleft()
        for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
            if 0 <=y+dy< n and 0<=x+dx<n:
                if d[y+dy][x+dx]-d[y][x]==2:
                    d[y+dy][x+dx] -= 1
                    que.append([x+dx, y+dy])
print(ans)

Submission status: Wrong Answer

Solution code:
import collections

N=int(input())
list = list(map(int, input().split()))
blist=[]
z=1
while(z<=N**2):
  blist.append(int(z))
  z+=1

def check(num):
  if(num<=N):
    return 0
  elif(N**2-N+1 <= num <= N**2):
    return 0
  elif(num % N==0):
    return 0
  elif(num % N==1):
    return 0
  else:
    i=1
    tmp1=0
    c=collections.Counter(blist)
    while(i<=N):
      if(c[num-N*i]!=0):
        tmp1+=1
      i+=1
    j=1
    tmp2=0
    while(j<=N):
      if(c[num+N*j]!=0):
        tmp2+=1
      j+=1
    tmp3=0
    p=num
    while(p % N !=0):
      p=p+1
      if(c[p]!=0):
        tmp3+=1
    tmp4=0
    q=num
    while(q % N !=1):
      q=q-1
      if(c[q]!=0):
        tmp4+=1
    if(tmp1==0 or tmp2==0 or tmp3==0 or tmp4==0):
      return 0
    else:
      tmplist=[]
      tmplist.append(tmp1)
      tmplist.append(tmp2)
      tmplist.append(tmp3)
      tmplist.append(tmp4)
      at=min(tmplist)
      return(at)
k=0
res=0
l=len(list)

while(k<l):
  a=list[k]
  blist.remove(a)
  if(check(a)!=0):
    res+=check(a)
  k+=1

print(res)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


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

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


def main():
    N = int(input())
    P = list(map(lambda x: int(x)-1, input().split()))

    bit = Bit(N)
    for i in range(1, N+1):
        bit.add(i, 1)

    rows = [Bit(N) for i in range(N)]
    cols = [Bit(N) for i in range(N)]
    for r in rows:
        r.tree = bit.tree.copy()
    for c in cols:
        c.tree = bit.tree.copy()

    ans = 0
    for p in P:
        # pの行番号、列番号
        r, c = divmod(p, N)
        # rowで抜ける場合
        t1 = rows[r].sum(c+1)          # 1-index
        t2 = rows[r].sum(N) - rows[r].sum(c)
        # colで抜ける場合
        t3 = cols[c].sum(r+1)          # 1-index
        t4 = cols[c].sum(N) - cols[c].sum(r)
        tt = min(t1, t2, t3, t4)
        ans += tt-1
        rows[r].add(c+1, -1)
        cols[c].add(r+1, -1)
    print(ans)
    return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
a=[int(i) for i in input().split()][::-1]
tate=[[0 for i in range(int(n))] for i in range(int(n))]
yoko=[[0 for i in range(int(n))] for i in range(int(n))]
ans=0

for i in a:
    yokoindex=[int((i-1)//n),int(i-int((i-1)//n)*n)-1]
    if i%n==0:
        tateindex=[int(n-1),int(i//n-1)]
    else:
        tateindex=[int(i%n-1),int(i//n)]
    if 1 not in yoko[yokoindex[0]][:yokoindex[1]] or 1 not in yoko[yokoindex[0]][yokoindex[1]+1:] or 1 not in tate[tateindex[0]][:tateindex[1]] or 1 not in tate[tateindex[0]][tateindex[1]+1:]:
        yoko[yokoindex[0]][yokoindex[1]]+=1
        tate[tateindex[0]][tateindex[1]]+=1
    else:
        ans+=1
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N = int(input())
    P = [int(i)-1 for i in input().split(' ')]
    seat = [[1 for j in range(N)] for i in range(N)]
    score = 0
    for i in range(len(P)):
        left = sum(seat[P[i]//N][:P[i]%N])
        right = sum(seat[P[i]//N][P[i]%N:])-1 if sum(seat[P[i]//N][P[i]%N:])-1>=0 else 0
        top = 0
        j = P[i]//N-1
        while True:
            if j >= 0:
                top += seat[j][P[i]%N]
            else:
                break
            j -= 1
        bottom = 0
        j = P[i]//N+1
        while True:
            if j < N:
                bottom += seat[j][P[i]%N]
            else:
                break
            j += 1
        score_direction = [left, right, top, bottom]
        score += min(score_direction)
        seat[P[i]//N][(P[i])%N] = 0
    print(score)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin

def checkans(N,arg,i):
    # 上をチェック
    uecount = 0
    bai = 1
    while (i + N * bai) <= len(arg)-1:
        # print(i+N*bai)
        if arg[i+N*bai] != 0:
            uecount += 1
        bai += 1
    # 下をチェック
    shitacount = 0
    bai = 1
    while i - N * bai >= 0:
        if arg[i - N * bai] != 0:
            shitacount += 1
        bai += 1
    # 右をチェック
    migicount = 0
    for a in range(i+1, N*(i//N+1)):
        if arg[a] != 0:
            migicount += 1
    # 左をチェック
    hidaricount = 0
    for a in range(N*(i//N),i):
        if arg[a] != 0:
            hidaricount += 1
    # print(f'uecount,shitacount,migicount,hidaricount {uecount} {shitacount} {migicount} {hidaricount}')
    return min(uecount, shitacount, migicount, hidaricount)

N = int(input())
P = list(map(int,stdin.readline().split()))
seki = [a+1 for a in range(N**2)]

ans = 0
for a,b in enumerate(P):
    ans += checkans(N,seki,b-1)
    seki[P[a]-1] = 0
    # print(f'ans = {ans}')
    # print(f'P = {seki}')

print(ans)

Submission status: Wrong Answer

Solution code:


def DFS(m,n,x,y,f,th):
    # print(x,y,th)
    if x in(0,n-1) or y in(0,n-1) or th >= min(n-x-1,n-y-1):
        return th

    r = (x+1)%n
    l = (x-1)%n
    t = (y+1)%n
    b = (y+1)%n
    flg = 999999999999
    if m[y][r] == 0 and f != 'l':
        flg = min(DFS(m,n,r,y,'r',th),flg)
    elif m[y][r] == 1 and f != 'l':
        flg = min(flg,DFS(m,n,r,y,'r',th+1))
    if m[y][l] == 0  and f != 'r':
        flg = min(flg,DFS (m,n,l,y,'l',th))
    elif m[y][l] == 1  and f != 'r':
        flg = min(flg,DFS (m,n,l,y,'l',th+1))
    if m[t][x] == 0 and f != 'b':
        flg = min(flg,DFS(m,n,x,t,'b',th))
    elif m[t][x] == 1 and f != 'b':
        flg = min(flg,DFS(m,n,x,t,'b',th+1))
    if m[b][x] == 0 and f != 't': 
        flg = min(flg,DFS(m,n,x,b,'t',th))
    elif m[b][x] == 1 and f != 't':
        flg = min(DFS(m,n,x,b,'t',th+1),flg)
    return flg



n = int(input())
p = [int(i)-1 for i in input().split()]
# print(p)


m = [[1] * n for i in range(n)]
# print(m)
c = 0
for i in p:
    x = i%n
    y = -(-(i+1)//n)-1 
    m[y][x] = 0
    c += (DFS(m,n,x,y,'',0))
    # print('aa',i+1,c)
        
    
print(c)

Submission status: Wrong Answer

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

p2i = {}

for i in range(N*N):
  p2i[i] = [(P[i]-1)//N, (P[i]-1)%N]

table = [[0 for j in range(N)] for i in range(N)]
for i in range(N*N):
  table[p2i[i][0]][p2i[i][1]] = i

S = 0

for n in range(N*N):
  above = 0
  below = 0
  left = 0
  right = 0
  for i in range(p2i[n][0]):
    above += (table[i][p2i[n][1]] != 0)
  for i in range(p2i[n][0]+1, N):
    below += (table[i][p2i[n][1]] != 0)
  for i in range(p2i[n][1]):
    left += (table[p2i[n][0]][i] != 0)
  for i in range(p2i[n][1]+1, N):
    right += (table[p2i[n][0]][i] != 0)

  S += min(above, below, left, right)
  table[p2i[n][0]][p2i[n][1]] = 0

print(S)