fun main(args: Array<String>) = println(run {
    val n= readLine()!!.toInt()
    val p = readLine()!!.split(" ").map { it.toInt() }
    val q = readLine()!!.split(" ").map { it.toInt() }

    var count = 0
    var start = listOf(p,q).minBy { it.joinToString("") }!!
    val end = listOf(p,q).maxBy { it.joinToString("") }!!

    while (start != end) {
        start = start.nextPermutation()
        count++
    }
    count
})

fun List<Int>.nextPermutation() = run {
    val n = this.size
    try {
        val i = (0..n - 2).last { this[it] < this[it + 1] }
        val j = this.indexOfLast { it > this[i] }
        this.take(i) + this[j] + (this.drop(i) - this[j]).sorted()
    } catch (e: Exception) {
        this.reversed()
    }
}