Problem:


Score : 700 points

Problem Statement

Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2.

At the end of the movie, the viewers go out of the cinema in a certain order: the i-th viewer leaving her seat is the one denoted by the number P_i. The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat.
To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column).
While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.

Compute the number of pairs of viewers (x, y) such that y will hate x forever.

Constraints

2 \le N \le 500

The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \{1, 2, \dots, N^2\}.

Input

The input is given from Standard Input in the format

N
P_1 P_2 \cdots P_{N^2}

Output

If ans is the number of pairs of viewers described in the statement, you should print on Standard Output

ans

Sample Input 1

3
1 3 7 9 5 4 8 6 2

Sample Output 1

1

Before the end of the movie, the viewers are arranged in the cinema as follows:

1 2 3
4 5 6
7 8 9

The first four viewers leaving the cinema (1, 3, 7, 9) can leave the cinema without going through any seat, so they will not be hated by anybody.

Then, viewer 5 must go through one of the seats where viewers 2, 4, 6, 8 are currently seated while leaving the cinema; hence he will be hated by at least one of those viewers.

Finally the remaining viewers can leave the cinema (in the order 4, 8, 6, 2) without going through any occupied seat (actually, they can leave the cinema without going through any seat at all).

Sample Input 2

4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8

Sample Output 2

3

Sample Input 3

6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30

Sample Output 3

11



Sample input:
3
1 3 7 9 5 4 8 6 2


Sample output:
1

Submission status: Wrong Answer

Solution code:
n = int(input())
p = list(map(int, input().split()))
s = [[0]*n for _ in range(n)]
ans = 0
def edge(N, i):
    if i % N == 0 or i % N == 1:
        return 1
    elif i > 1 and i <N:
        return 1
    elif i > N**2-N+1 and i<N**2:
        return 1
    else:
        return 0
    
def check(n, s, r, c):
    b =  1
    
    
    if not r ==0: #縦↑
        for j in range(r):
            if s[j][c]==0:
                b = 0
        if b==1:return 1
        else:b=1
        
    if not r == n-1: #縦↓
        for j in range(r+1, n):
            if s[j][c]==0:
                b = 0
        if b==1:return 1
        else:b=1
        
    if not c == 0: #横←
        for j in range(c):
            if s[r][j]==0:
                b = 0
        if b==1:return 1
        else:b=1
        
    if not c == n-1: #縦↓
        for j in range(c+1, n):
            if s[r][j]==0:
                b = 0
        if b==1:return 1  
    return 0


def mini(n, s, r, c):
    
    adisg = 10**100
    if not r ==0: #縦↑
        disg = 0
        for j in range(r):
            if s[j][c]==0:
                disg +=1
        adisg = min(adisg, disg)
        
    if not r == n-1: #縦↓
        disg = 0
        for j in range(r+1, n):
            if s[j][c]==0:
                disg +=1
        adisg = min(adisg, disg)
        
    if not c == 0: #横←
        disg = 0
        for j in range(c):
            if s[r][j]==0:
                disg +=1
        adisg = min(adisg, disg)
        
    if not c == n-1: #縦↓
        disg = 0
        for j in range(c+1, n):
            if s[r][j]==0:
                disg +=1
        adisg = min(adisg, disg)
    return adisg

for i in p:
    if i % n ==0:
        r = i//n-1
        c = n-1
    else:
        r = i//n
        c = i%n-1

    if edge(n, i):
        s[r][c] = 1
    
        continue
    elif check(n, s, r, c):
        s[r][c] = 1
      
        continue
    else:
        s[r][c] = 1
        ans += mini(n, s, r, c)
        
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

N = int(input())
a = [int(i) for i in input().split()]

ans = 0
array = np.array([np.arange(N*i+1, N*(i+1)+1)for i in range(N)])
for i in a:
    if i % N == 0:
        array[i//N - 1, -1] = 0
    else:
        row = i//N
        col = i % N - 1
        array[row, col] = 0
        if col == 0:
            continue
        r = array[row]
        rl = np.sum(r[0:col] != 0)
        if rl == 0:
            continue
        rr = np.sum(r[col:] != 0)
        if rr == 0:
            continue
        c = array[:, col]
        ct = np.sum(c[0:row] != 0)
        if ct == 0:
            continue
        cb = np.sum(c[row:] != 0)
        if cb == 0:
            continue
        ans += min(rl, rr, ct, cb)
print(ans)

Submission status: Wrong Answer

Solution code:
import math

def find(x,n):
    row = int(math.ceil(x/n))
    x %= n
    if x == 0:
        col = n
    else:
        col = x

    return row,col 

def sumQuery(BIT,index):
    if index > len(BIT)-1:
        return 0
    total = 0
    while index > 0:
        #print(index)
        total += BIT[index]
        index -= index&-index

    return total

def update(BIT,index,val):
    while index < len(BIT):
        BIT[index] += val
        index += index&-index

def main():
    n = int(input())
    arr = list(map(int,input().split()))

    row_BITS = [[0 for j in range(n+1)] for i in range(n)]
    col_BITS = [[0 for j in range(n+1)] for i in range(n)]
    for i in range(n):
        for j in range(1,n+1):
            update(row_BITS[i],j,1)
            update(col_BITS[i],j,1)

    ans = 0
    for i in arr:
        row,col = find(i,n)
        left = sumQuery(row_BITS[row-1],col-1)
        right = sumQuery(row_BITS[row-1],n)-sumQuery(row_BITS[row-1],col)
        up = sumQuery(col_BITS[col-1],row-1)
        down = sumQuery(col_BITS[col-1],n)-sumQuery(col_BITS[col-1],row)
        min_val = min(left,right,up,down)
        ans += min_val
        update(row_BITS[row-1],col,-1)
        update(col_BITS[col-1],row,-1)
        
    print(ans)

main()

Submission status: Wrong Answer

Solution code:
n = int(input())
p = list(map(int, input().split()))
n_list = []
n_reverse_list = []
for i in range(1, n+1):
  n_list.append(list(range((i-1)*n+1, i*n+1)))
  n_reverse_list.append(list(range(i, n**2+i+1-n, n)))
ans = 0
for i in p:
  row = (i - 1)//n
  column = (i - 1)%n
  n_list[row][column] = 0
  n_reverse_list[row][column] = 0
  a = len(n_list[row][:column]) - n_list[row][:column].count(0)
  b = len(n_list[row][column+1:]) - n_list[row][column+1:].count(0)
  c = len(n_reverse_list[row][:column]) - n_reverse_list[row][:column].count(0)
  d = len(n_reverse_list[row][column+1:]) - n_reverse_list[row][column+1:].count(0)
  ans += min(a, b, c, d)
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
p=list(map(int,input().split()))
seat=['0'*n]*n
answer=0
for i in range(n**2):
    row=p[i]//n
    if p[i]%n==0:
        row-=1
    lin=p[i]%n-1
    if lin<0:
        lin=n-1
    hate=min(seat[row][:lin].count('0'),seat[row][lin+1:].count('0'))
    t=0
    s=0
    for j in range(n-1):
        if j<row:
            if seat[j][lin]=='0':
                t+=1
        if n-j-1>row:
            if seat[-j-1][lin]=='0':
                s+=1
    answer+=min(hate,t,s)
    seat[row]=seat[row][:lin]+'1'+seat[row][lin+1:]
print(answer)

Submission status: Wrong Answer

Solution code:
import numpy as np
n = int(input())
p = list(map(int, input().split()))
n_list = list(range(1, n**2 + 1))
n_array = np.arange(1, n**2 + 1).reshape(n, n)
ans = 0
for i in p:
  row = (i - 1)//n
  column = (i - 1)%n
  n_array[row, column] = 0
  a = np.count_nonzero(n_array[row, :column], axis=0)
  b = np.count_nonzero(n_array[row, column+1:], axis=0)
  c = np.count_nonzero(n_array[:row, column], axis=0)
  d = np.count_nonzero(n_array[row+1:, column], axis=0)
  ans += min(a, b, c, d)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

def leave(n, L):
    
    class Node():
        
        def __init__(self, val):
            self.val = val
            self.N = None
            self.S = None
            self.W = None
            self.E = None
            
    nodes = [Node(i) for i in range(n*n+1)]
    hates = 0
            
    def bfs(k):
        depth = 0
        node = nodes[k]
        queue = deque()
        queue.append(node)
        
        while True:
            length = len(queue)
            for i in range(length):
                node = queue.popleft()
                if node == None:
                    return depth - 1
                queue.append(node.N)
                queue.append(node.S)
                queue.append(node.W)
                queue.append(node.E)
            depth += 1
            
    
    for i in range(1, n*n+1):
        if i <= n * n - n:
            nodes[i].N = nodes[i+n]
        if i > n:
            nodes[i].S = nodes[i-n]
        if i % n:
            nodes[i].E = nodes[i+1]
        if i % n != 1:
            nodes[i].W = nodes[i-1]
            
    for k in L:
        hates += bfs(k)
        node = nodes[k]
        if node.N:
            node.N.S = node.S
        if node.S:
            node.S.N = node.N
        if node.W:
            node.W.E = node.E
        if node.E:
            node.E.W = node.W
        
    return hates
        
n = int(input())
L = [int(s) for s in input().split()]
print(leave(n, L))

Submission status: Wrong Answer

Solution code:
n=int(input())
print(n**2)

Submission status: Wrong Answer

Solution code:
n = int(input())
ps = list(map(int, input().split()))
rem_num = {i: {"l": 0, "r": 0, "u": 0, "b": 0} for i in range(1, n*n+1)}

for i in range(1, n*n+1):
    rem_num[i]["u"] = (i-1)//n
    rem_num[i]["b"] = n - (i-1)//n - 1
    rem_num[i]["l"] = (i-1) % n
    rem_num[i]["r"] = n - (i-1) % n - 1

ans = 0
for p in ps:
    # print(f"{p} {rem_num[p]} {min(rem_num[p].values())}")
    ans += min(rem_num[p].values())
    for i in range(p + n, n*n+1, n):
        rem_num[i]["u"] -= 1
    for i in range(p - n, 0, -n):
        rem_num[i]["b"] -= 1
    for i in range(p + 1, n*((p-1)//n + 1)):
        rem_num[i]["l"] -= 1
    for i in range(p - 1, n*((p-1)//n), -1):
        rem_num[i]["r"] -= 1

print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
l=list(map(int, input().split()))
l1=[[0 for i in range(n)] for j in range(n)]
k=1
cnt=0
for i in range(n):
    for j in range(n):
        l1[i][j]=k
        k=k+1
for i in l:
    r=i/n
    if r!=int(r):
        r=int(r)
    else:
        r=int(r)-1
    c=(i%n)-1
    if c==-1:
        c=n-1
    if r==0 or r==n-1 or c==0 or c==n-1:
        l1[r][c]=0
    else:
        val=0
        num1=0
        num2=0
        num3=0
        num4=0
        for h in range(r):
            if l1[h][c]!=0:
                val=1
                num1=num1+1
        if val==1:
            val=0
            for h in range(r+1,n):
                if l1[h][c]!=0:
                    val=1
                    num2=num2+1
                    if num2>num1:
                        break
            if val==1:
                val=0
                for h in range(c):
                    if l1[r][h]!=0:
                        val=1
                        num3=num3+1
                        if num3>num1 or num3>num2:
                            break
                if val==1:
                    val=0
                    for h in range(c+1,n):
                        if l1[r][h]!=0:
                            val=1
                            num4=num4+1
                            if num4>num3 or num4>num2 or num4>num1:
                                break
                    if val==1:
                        l9=[]
                        l9.append(num1)
                        l9.append(num2)
                        l9.append(num3)
                        l9.append(num4)
                        cnt=cnt+min(l9)
        l1[r][c]=0
print(cnt)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

class SegmentTree():
    def __init__(self, n):
        self.n = 2 ** (n - 1).bit_length()
        self.data = [1] * (2 * self.n)

    def build(self):
        for k in reversed(range(self.n - 1)):
            self.data[k] = self.data[k * 2 + 1] + self.data[k * 2 + 2]

    def update(self, k, a):
        k += self.n - 1
        self.data[k] = a

        while k > 0:
            k = (k - 1) // 2
            self.data[k] = self.data[k * 2 + 1] + self.data[k * 2 + 2]

    def query(self, l, r):
        L = l + self.n
        R = r + self.n
        ret = 0
        while L < R:
            if R & 1:
                R -= 1
                ret += self.data[R - 1]
            if L & 1:
                ret += self.data[L - 1]
                L += 1
            L >>= 1
            R >>= 1
        return ret

N = int(input())
Q = list(map(int, input().split()))
X_Seg = [SegmentTree(N) for _ in range(N)]
Y_Seg = [SegmentTree(N) for _ in range(N)]
for i in range(N):
    X_Seg[i].build()
    Y_Seg[i].build()

ans = 0

for k in Q:
    k -= 1
    x, y = k % N, k // N

    X_Seg[y].update(x, 0)
    Y_Seg[x].update(y, 0)

    ret = 10**5
    if x == 0 or x == N - 1 or y == 0 or y == N - 1:
        ret = 0
    else:
        L = X_Seg[y].query(0, x)
        R = X_Seg[y].query(x, N)
        U = Y_Seg[x].query(0, y)
        D = Y_Seg[x].query(y, N)
        ret = min(ret, min([L, R, U, D]))
    ans += ret

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
from math import floor, sqrt, factorial, hypot, log  # log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter, defaultdict, deque
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint


def ceil(a, b): return (a + b - 1) // b


inf = float('inf')
mod = 10 ** 9 + 7


def pprint(*A):
    for a in A:     print(*a, sep='\n')


def INT_(n): return int(n) - 1


def MI(): return map(int, input().split())


def MF(): return map(float, input().split())


def MI_(): return map(INT_, input().split())


def LI(): return list(MI())


def LI_(): return [int(x) - 1 for x in input().split()]


def LF(): return list(MF())


def LIN(n: int): return [I() for _ in range(n)]


def LLIN(n: int): return [LI() for _ in range(n)]


def LLIN_(n: int): return [LI_() for _ in range(n)]


def LLI(): return [list(map(int, l.split())) for l in input()]


def I(): return int(input())


def F(): return float(input())


def ST(): return input().replace('\n', '')


def main():
    N = I()
    P = MI()
    emp = [[False] * (N + 1) for _ in range(N + 1)]
    dp = [[inf] * (N + 1) for _ in range(N + 1)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    for x in range(1, N + 1):
        for y in range(1, N + 1):
            ax = min(x - 1, N - x)
            ay = min(y - 1, N - y)
            dp[x][y] = min(ax, ay)
    ans = 0
    for i in P:
        x = (i % N)
        y = (i // N) + 1
        if x == 0:
            x += N
            y -= 1
        ans += dp[x][y]
        emp[x][y] = True
        q = deque([(x, y)])
        used = []
        while q:
            now = q.popleft()
            used.append(now)
            for j in range(len(dx)):
                nx = now[0] + dx[j]
                ny = now[1] + dy[j]
                if 1 <= nx <= N and 1 <= ny <= N and dp[nx][ny] > dp[now[0]][now[1]]:
                    dp[nx][ny] = dp[now[0]][now[1]]
                    if emp[nx][ny] and not used.__contains__((nx, ny)):
                        q.append((nx, ny))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np

N = int(input())

table = np.array([[1 for i in range(N)] for j in range(N)])


pattern = 0

peaple = list(map(int,input().split()))


for person in peaple:
    person -= 1
    row = person//N
    column = person%N
    table[row][column] = 0
    if column in [0,N-1] or row in [0,N-1]:
        continue;
    person_row = list(table[row])
    person_column = list(table[:,column])
    around = [sum(person_row[:column]),sum(person_row[column+1:]),sum(person_column[:row]),sum(person_column[row+1:])]
    around.sort()
    for j in around:
        if j == 0:
            break;
        else:
            pattern += j
            break;


print(pattern)

Submission status: Wrong Answer

Solution code:
N=int(input())
P=input().split(' ')
for i in range(N**2):
    P[i]=int(P[i])
M=[[1] * N for i in range(N)]
Hate=0
for ij in range(N**2):
    j=(int(P[ij])-1)%N
    i=(int(P[ij])-1)//N
    K1=0
    K2=0
    K3=0
    K4=0
    M[i][j]=0
    for k in range(0,i):
        if M[k][j]==1:
            K1+=1
    for k in range(i,N):
        if M[k][j]==1:
            K2+=1
    for k in range(0,j):
        if M[i][k]==1:
            K3+=1
    for k in range(j,N):
        if M[i][k]==1:
            K4+=1
    Hate+=min(K1,K2,K3,K4)
print(Hate)

Submission status: Wrong Answer

Solution code:
N=int(input())
P=input().split()
M = [[1] * N for i in range(N)]
Hate=0
for ij in range(N**2):
    j=(int(P[ij])-1)%N
    i=(int(P[ij])-1)//N
    K1=0
    K2=0
    K3=0
    K4=0
    M[i][j]=0
    for k in range(0,i):
        if M[k][j]==1:
            K1+=1
    for k in range(i,N):
        if M[k][j]==1:
            K2+=1
    for k in range(0,j):
        if M[i][k]==1:
            K3+=1
    for k in range(j,N):
        if M[i][k]==1:
            K4+=1
    Hate+=min(K1,K2,K3,K4)
print(Hate)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import numpy as np

# input
N = int(input())
P = (input().split())

#process
S = np.zeros((N, N))
ans = 0
for p in P:
    row = math.ceil(int(p)/N) - 1
    col = (N - 1) if (math.ceil(int(p)%N) - 1) == -1 else math.ceil(int(p)%N) - 1
    S[row][col] = 1
    up = S[row,:col]
    down = S[row,col+1:]
    left = S[:row,col]
    right = S[row+1:,col]
    if len(up) <= 0 or len(down) <= 0 or len(left) <= 0 or len(right) <= 0 :
        continue
    else:
        minCount = [np.count_nonzero(up == 0),np.count_nonzero(down == 0),np.count_nonzero(left == 0),np.count_nonzero(right == 0)]
        ans = ans + min(minCount)

#output
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
l=list(map(int,input().split()))
l1=l.copy()
a=0
for i in l:
    if(i%n==1 or i%n==0 or (i>=1 and i<=n) or (i>=n*n - n+1 and i<=n*n)):
        l1.remove(i)
    else:
        p=i%n
        q=n-i%n
        x=0
        for j in range(i+1,i+1+q):
            x+=l1.count(j)
        if(x==0):
            l1.remove(i)
            continue
        y=0
        for j in range(i-p+1,i):
            y+=l1.count(j)
        if(y==0):
            l1.remove(i)
            continue
        z=0
        for j in range(i%n,i+1,n):
            z+=l1.count(j)
        if(z==0):
            l1.remove(i)
            continue
        w=0
        for j in range(i+1,n*n-n+p+1,n):
            w+=l1.count(j)
        if(w==0):
            l1.remove(i)
            continue
        a+=min(x,y,z,w)
        l1.remove(i)
print(a)

Submission status: Wrong Answer

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

from collections import deque
q = deque()

space = [1]*(n*n)

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

ans = 0
for pi in p:
    row, col = divmod(pi-1, n)

    q.clear()
    q.append((row, col))

    dist = [-1]*(n*n)
    dist[row*n+col] = 0

    ret = list()
    while q:
        ph, pw = q.popleft()
        for dyi, dxi in zip(dy,dx):
            if 0<=ph+dyi<n and 0<=pw+dxi<n:
                if dist[(ph+dyi)*n+(pw+dxi)] == -1:
                    q.append((ph+dyi,pw+dxi))
                    dist[(ph+dyi)*n+(pw+dxi)] = dist[ph*n+pw]+int(space[(ph+dyi)*n+(pw+dxi)]==1)
            else:
                ret.append(dist[ph*n+pw])
    ans += min(ret)
    space[row*n + col] = 0

print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
from math import floor, sqrt, factorial, hypot, log  # log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter, defaultdict, deque
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint


def ceil(a, b): return (a + b - 1) // b


inf = float('inf')
mod = 10 ** 9 + 7


def pprint(*A):
    for a in A:     print(*a, sep='\n')


def INT_(n): return int(n) - 1


def MI(): return map(int, input().split())


def MF(): return map(float, input().split())


def MI_(): return map(INT_, input().split())


def LI(): return list(MI())


def LI_(): return [int(x) - 1 for x in input().split()]


def LF(): return list(MF())


def LIN(n: int): return [I() for _ in range(n)]


def LLIN(n: int): return [LI() for _ in range(n)]


def LLIN_(n: int): return [LI_() for _ in range(n)]


def LLI(): return [list(map(int, l.split())) for l in input()]


def I(): return int(input())


def F(): return float(input())


def ST(): return input().replace('\n', '')


def main():
    N = I()
    P = MI()
    emp = [[False] * (N + 1) for _ in range(N + 1)]
    dp = [[inf] * (N + 1) for _ in range(N + 1)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    for x in range(1, N + 1):
        for y in range(1, N + 1):
            ax = min(x - 1, N - x)
            ay = min(y - 1, N - y)
            dp[x][y] = min(ax, ay)
    ans = 0
    for i in P:
        x = (i % N)
        y = (i // N) + 1
        if x == 0:
            x += N
            y -= 1
        ans += dp[x][y]
        emp[x][y] = True
        q = deque([(x, y)])
        while q:
            now = q.popleft()
            for j in range(len(dx)):
                nx = now[0] + dx[j]
                ny = now[1] + dy[j]
                if 1 <= nx <= N and 1 <= ny <= N and dp[nx][ny] > dp[now[0]][now[1]]:
                    dp[nx][ny] = dp[now[0]][now[1]]
                    if emp[nx][ny]:
                        q.append((nx, ny))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
l=list(map(int, input().split()))
l1=[[0 for i in range(n)] for j in range(n)]
k=1
cnt=0
for i in range(n):
    for j in range(n):
        l1[i][j]=k
        k=k+1
for i in l:
    r=i/n
    if r!=int(r):
        r=int(r)
    else:
        r=int(r)-1
    c=(i%n)-1
    if c==-1:
        c=n-1
    if r==0 or r==n-1 or c==0 or c==n-1:
        l1[r][c]=0
    else:
        val=0
        num1=0
        num2=0
        num3=0
        num4=0
        for h in range(r):
            if l1[h][c]!=0:
                val=1
                num1=num1+1
        if val==1:
            val=0
            for h in range(r+1,n):
                if l1[h][c]!=0:
                    val=1
                    num2=num2+1
            if val==1:
                val=0
                for h in range(c):
                    if l1[r][h]!=0:
                        val=1
                        num3=num3+1
                if val==1:
                    val=0
                    for h in range(c+1,n):
                        if l1[r][h]!=0:
                            val=1
                            num4=num4+1
                    if val==1:
                        l9=[]
                        l9.append(num1)
                        l9.append(num2)
                        l9.append(num3)
                        l9.append(num4)
                        cnt=cnt+min(l9)
        l1[r][c]=0
print(cnt)

Submission status: Wrong Answer

Solution code:
def init(n):
    d = {}
    for i in range(n*n):
        x, y = i // n, i % n
        left = i - x * n
        right = (x+1) * n - 1 - i
        top = (i - y) // n
        bottom = (n * (n-1) + y - i) // n
        d[i] = [left, top, right, bottom]
    return d

def update(dic, cur, n):
    x, y = cur // n, cur % n
    left = x * n
    right = (x+1) * n - 1
    top = y
    bottom = n * (n-1) + y
    for i in range(left, cur):
        dic[i][2] -= 1
    for i in range(cur+1, right+1):
        dic[i][0] -= 1
    for i in range(top, cur, n):
        dic[i][3] -= 1
    for i in range(cur+n, bottom, n):
        dic[i][1] -= 1

#[left, up, right, bottom]
N = int(input())
P = list(map(int, input().split()))
d = init(N)
ans = 0
# print(d)
for p in P:
    ans += min(d[p-1])
    update(d, p-1, N)
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
l=list(map(int,input().split()))
l1=l.copy()
a=0
for i in l:
    if(i%n==1 or i%n==0 or (i>=1 and i<=n) or (i>=n*n - n+1 and i<=n*n)):
        l1.remove(i)
    else:
        p=i%n
        q=n-i%n
        x=0
        for j in range(i+1,i+1+q):
            x+=l1.count(j)
        y=0
        for j in range(i-p+1,i):
            y+=l1.count(j)
        z=0
        for j in range(i%n,i+1,n):
            z+=l1.count(j)
        w=0
        for j in range(i+1,n*n-n+p+1,n):
            w+=l1.count(j)
        a+=min(x,y,z,w)
        l1.remove(i)
print(a)

Submission status: Wrong Answer

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

from collections import deque

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

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

ans = 0
for pi in p:
    row, col = divmod(pi-1, n)
    dist = np.full(n*n, -1).reshape(n,n)
    ret = list()
    q = deque()
    q.append((row, col))
    dist[row, col] = 0
    while q:
        ph, pw = q.popleft()
        for dyi, dxi in zip(dy,dx):
            if 0<=ph+dyi<n and 0<=pw+dxi<n:
                if dist[ph+dyi,pw+dxi] == -1:
                    q.append((ph+dyi,pw+dxi))
                    dist[ph+dyi,pw+dxi] = dist[ph,pw]+int(space[ph+dyi,pw+dxi]==1)
            else:
                ret.append(dist[ph,pw])
    ans += min(ret)
    space[row, col] = 0

print(int(ans))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

N = int(input())
P = list(map(int, input().split()))
seat = [False] * N ** 2
ans = 0

for p in P:
  p -= 1
  seat[p] = True
  x = p % N
  y = p // N
  seatX = [n for n in range(x, N**2, N)]
  seatY = [n for n in range(N*y, N*(y+1))]
  up = []
  down = []
  right = []
  left = []
  for sx in seatX:
    if sx < p:
      up.append(seat[sx])
    elif sx > p:
      down.append(seat[sx])
  for sy in seatY:
    if sy < p:
      left.append(seat[sy])
    elif sy > p:
      right.append(seat[sy])
  upc = up.count(False)
  downc = down.count(False)
  rightc = right.count(False)
  leftc = left.count(False)
  move = min(upc, downc, rightc, leftc)
  ans += move


print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
Ps = list(map(int, input().split()))
fields = [[0]*n for i in range(n)]

for i in range(n**2):
    fields[i//n][i%n] = i

def hw(p):
    h = (p-1)//n
    w = (p-1)%n
    return h+1,w+1

class BIT:
    def __init__(self, n):
        """
        初期化
        Input:　
            n: 配列の大きさ
        """
        self.n = n
        self.bit = [0] * (n+10)

    def add(self, x, w):
        """
        更新クエリ(add)
        Input:
            x: インデックス
            w: 加える値
        Note:
            self.bitが更新される
        """        
        while x <= self.n:
            self.bit[x] += w
            x += x&-x
    
    def sum(self, x):
        """
        部分和算出クエリ
        Input:
            x: インデックス
        Return:
            [1,a]の部分和
        """
        cnt = 0
        while x > 0:
            cnt += self.bit[x]
            # 次の最下位桁はどこか
            x -= x&-x
        return cnt   
    
    def psum(self, a, b):
        """
        区間[a,b)(0-indexed)における和
        Input
            a,b: 半開区間
        Return
            [a,b)の和
        """
        return self.sum(b-1) - self.sum(a-1)
    
    def bisect(self, w):
        """
        二分探索クエリ
        (すべての要素が0以上のとき)
        Input:
            w: 値
        Return:
            w以上となる最小のindex
        """    
        if w <= 0: return 0
        x = 0 #index
        k = 1
        while k < self.n:
            k *= 2

        while k > 0:
            if x + k <= self.n and self.bit[x+k] < w:
                # 右に移動
                w -= self.bit[x+k]
                x += k
            k //= 2 
        return x + 1
    
# H側のBIT
hbits = [0]
for i in range(n):
    bit = BIT(n)
    for i in range(n):
        bit.add(i+1,1)
    hbits.append(bit)
# W側のBIT
wbits = [0]
for i in range(n):
    bit = BIT(n)
    for i in range(n):
        bit.add(i+1,1)
    wbits.append(bit)

ans = 0
# print(Ps)
for p in Ps:
    h, w = hw(p)
    h1 = hbits[h].sum(w-1)
    h2 = hbits[h].psum(w+1,n+1)
    w1 = wbits[w].sum(h-1)
    w2 = wbits[w].psum(h+1,n+1)
    # print(h,w,(h1,h2,w1,w2))
    ans += min(h1,h2,w1,w2)
    hbits[h].add(w, -1)
    wbits[w].add(h, -1)
print(ans)

Submission status: Wrong Answer

Solution code:
print("1")

Submission status: Wrong Answer

Solution code:
n = int(input())
seat = [[True]*n for i in range(n)]
lst = list(map(int, input().split()))

def place(m):
  m -= 1
  return [m//n, m%n]

ans = 0
for i in range(n**2):
  h = place(lst[i])
  seat[h[0]][h[1]] = False
  score = float('inf')
  
  can = 0
  for j in range(h[0]+1):
    if seat[h[0]-j][h[1]]:
      can += 1
  score = min(score, can)
  
  can = 0
  for j in range(n-h[0]):
    if seat[h[0]+j][h[1]]:
      can += 1
  score = min(score, can)
  
  can = 0
  for j in range(h[1]+1):
    if seat[h[0]][h[1]-j]:
      can += 1
  score = min(score, can)
  
  can = 0
  for j in range(n-h[1]):
    if seat[h[0]][h[1]+j]:
      can += 1
  score = min(score, can)
  
  ans += score

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
p = list(map(int, input().split()))
a = [[1]*n for i in range(n)]

ans = 0
for i in range(len(p)):
    # print(a)
    p[i] -= 1
    a[p[i] // n][p[i] % n] = 0
    s1 = 0;
    for j in range(p[i] % n, n):
        s1 += a[p[i] // n][j]
    s2 = 0
    for j in range(p[i] % n, -1, -1):
        s2 += a[p[i] // n][j]
    s3 = 0
    for j in range(p[i] // n, n):
        s3 += a[j][p[i] % n]
    s4 = 0
    for j in range(p[i] // n, -1, -1):
        s4 += a[j][p[i] % n]
    ans += min(s1, s2, s3, s4)
print(ans)

Submission status: Wrong Answer

Solution code:
def check(left, cur, n):
    x, y = cur // n, cur % n
    l, r = x * n, x * n + (n-1)
    top, bot = y, n * (n-1) + y
    res = n
    foo = lambda x: x not in left
    res = min(res, len(list(filter(foo, range(l, cur)))))
    res = min(res, len(list(filter(foo, range(cur+1, r+1)))))
    res = min(res, len(list(filter(foo, range(top, cur, n)))))
    res = min(res, len(list(filter(foo, range(cur+1, bot, n)))))
    # print(cur, res)
    return res

N = int(input())
P = list(map(int, input().split()))
left = set()
ans = 0
for p in P:
    ans += check(left, p-1, N)
    left.add(p-1)
print(ans)