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

Solution in Kotlin (1.3.71) (judge verdict: Accepted)

@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")

import java.io.PrintWriter
import kotlin.math.*
import kotlin.random.Random
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
    object {
        val n = readInt()
        val P = IntArray(n * n) { readInt() - 1 }

        val occ = Array(n) { BooleanArray(n) { true } }

        val C = Array(n) { i ->
            IntArray(n) { j ->
                minOf(i, n-1-i, j, n-1-j)
            }
        }

        var ans = 0

        inline fun forEachNeighbor(i: Int, j: Int, yield: (ni: Int, nj: Int) -> Unit) {
            if(i > 0) yield(i-1, j)
            if(i < n-1) yield(i+1, j)
            if(j > 0) yield(i, j-1)
            if(j < n-1) yield(i, j+1)
        }

        init {
            for(p in P) {
                val pi = p / n
                val pj = p - n * pi

                ans += C[pi][pj]
                occ[pi][pj] = false

                val Q = IntDeque()
                Q.add(pi)
                Q.add(pj)

                while(Q.isNotEmpty()) {
                    val i = Q.remove()
                    val j = Q.remove()
                    val c = C[i][j] + if(occ[i][j]) 1 else 0

                    forEachNeighbor(i, j) { ni, nj ->
                        if(C[ni].setMin(nj, c)) {
                            Q.add(ni)
                            Q.add(nj)
                        }
                    }
                }

            }

            println(ans)
        }

    }
}

fun minOf(first: Int, vararg rest: Int) = rest.fold(first, ::min)
fun IntArray.setMin(i: Int, v: Int) = if(v < get(i)) { set(i, v); true } else false

class IntDeque(capacity: Int = 12){
    private var arr = IntArray(capacity)
    var size = 0
        private set
    inline val lastIndex get() = size - 1
    inline val indices get() = 0 until size

    private inline val capacity get() = arr.size

    inline fun isEmpty() = size == 0
    inline fun isNotEmpty() = size != 0

    private var head = 0

    private fun grow(minCapacity: Int = 8) {
        val newCapacity = maxOf(minCapacity, capacity + (capacity shr 1))
        val new = IntArray(newCapacity)
        for(i in 0 until size) new[i] = get(i)
        arr = new
        head = 0
    }

    private fun incHead() {
        head++
        if(head == capacity) head = 0
    }

    private fun decHead() {
        if(head == 0) head = capacity - 1
        else head--
    }

    private fun index(i: Int) = (head + i).let { if(it >= capacity) it - capacity else it }

    fun add(index: Int, element: Int) {
        if(size == capacity) grow()
        if(index < size / 2) {
            decHead()
            size++
            for(i in 0 until index) {
                set(i, get(i+1))
            }
        } else {
            size++
            for(i in size - 2 downTo index) {
                set(i+1, get(i))
            }
        }
        set(index, element)
    }

    fun addLast(e: Int) {
        if(size == capacity) grow()
        arr[index(size)] = e
        size++
    }
    inline fun add(e: Int) = addLast(e)

    val first get() = get(0)
    val last get() = get(lastIndex)

    fun removeFirst(): Int {
        val e = get(0)
        incHead()
        size--
        return e
    }
    inline fun remove() = removeFirst()
    fun removeLast(): Int {
        val e = get(lastIndex)
        size--
        return e
    }

    fun addFirst(e: Int) {
        if(size == capacity) grow()
        decHead()
        arr[head] = e
        size++
    }

    operator fun get(index: Int): Int {
        require(index in 0 until size)
        return arr[index(index)]
    }

    fun removeAt(index: Int): Int {
        val e = get(index)
        if(index < size / 2) {
            for(i in index - 1 downTo 0) {
                set(i+1, get(i))
            }
            incHead()
        } else {
            for(i in index until size - 1) {
                set(i, get(i+1))
            }
        }
        size--
        return e
    }

    operator fun set(index: Int, element: Int): Int {
        val old = get(index)
        arr[index(index)] = element
        return old
    }

    operator fun iterator() = object: IntIterator() {
        var i = 0
        override fun hasNext(): Boolean = i < size
        override fun nextInt(): Int = get(i++)
    }
}


/** IO */
//@JvmField val INPUT = File("input.txt").inputStream()
//@JvmField val OUTPUT = File("output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

const val _BUFFER_SIZE = 1 shl 16
@JvmField val _buffer = ByteArray(_BUFFER_SIZE)
@JvmField var _bufferPt = 0
@JvmField var _bytesRead = 0

tailrec fun readChar(): Char {
    if(_bufferPt == _bytesRead) {
        _bufferPt = 0
        _bytesRead = INPUT.read(_buffer, 0, _BUFFER_SIZE)
    }
    return if(_bytesRead < 0) Char.MIN_VALUE
    else {
        val c = _buffer[_bufferPt++].toChar()
        if (c == '\r') readChar()
        else c
    }
}

fun readLine(): String? {
    var c = readChar()
    return if(c == Char.MIN_VALUE) null
    else buildString {
        while(true) {
            when(c) {
                '\n', Char.MIN_VALUE -> return@buildString
                else -> {
                    append(c)
                    c = readChar()
                }
            }
        }
    }
}
fun readLn() = readLine()!!

fun read() = buildString {
    var c = readChar()
    while(c <= ' ') {
        if(c == Char.MIN_VALUE) return@buildString
        c = readChar()
    }
    do {
        append(c)
        c = readChar()
    } while(c > ' ')
}
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <T> _shuffle(rnd: Random, get: (Int) -> T, set: (Int, T) -> Unit, size: Int) {
    // Fisher-Yates shuffle algorithm
    for (i in size - 1 downTo 1) {
        val j = rnd.nextInt(i + 1)
        val temp = get(i)
        set(i, get(j))
        set(j, temp)
    }
}

@JvmField var _random: Random? = null
val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it }

fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun IntArray.sort() { shuffle(); _sort() }
fun IntArray.sortDescending() { shuffle(); _sortDescending() }

fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun LongArray.sort() { shuffle(); _sort() }
fun LongArray.sortDescending() { shuffle(); _sortDescending() }

fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun DoubleArray.sort() { shuffle(); _sort() }
fun DoubleArray.sortDescending() { shuffle(); _sortDescending() }

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T: Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()

fun `please stop removing these imports IntelliJ`() { iprintln(max(1, 2)) }

/** additional commons */
inline fun <T> Iterable<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Sequence<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Array<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
fun IntArray.sumLong() = fold(0L, Long::plus)