
fun main(args:Array<String>):Unit {
    val n = readLine()!!.toInt()
    val max = factorial(n)
    val narabi = readLine()!!.split(' ').map(String::toInt).toTypedArray()
    val rank = toRank(narabi)
    println(listOf(-1, 0, 1).map{it + rank}.filter{it in 0 until max}.joinToString ("\n"){
        toPermutation(n, it).joinToString(" ")
    })
}
fun factorial(n:Int):Int{
    return when(n){
        0 -> 1
        else -> n * factorial(n - 1)
    }
}
fun toPermutation(length:Int, value:Int):Array<Int>{
    val res = Array(length){it + 1}
    var num = value
    for (i in 0 until length){
        val n = num / factorial(length - 1 - i)
        val temp = res[i + n]
        for (j in n downTo 1) res[i + j] = res[i + j - 1]
        res[i] = temp
        num %= factorial(length - 1 - i)
    }
    return res
}
fun toRank(array:Array<Int>):Int {
    val res = Array(array.size){it + 1}
    var num = 0
    for (i in 0 until array.size){
        val n = res.indexOfFirst { it == array[i] } - i
        num += n * factorial(array.size - 1 - i)
        val temp = res[i + n]
        for (j in n downTo 1) res[i + j] = res[i + j - 1]
        res[i] = temp
    }
    return num
}
