const val MOD = 998_244_353

fun main() {
    val testsN = readln().toInt()
    repeat(testsN) {
        val n = readln().toInt()
        val initialState = readState()
        val goalState = readState()
        var distance = (distFromStart(goalState) - distFromStart(initialState) + MOD) % MOD
        if (lexLess(goalState, initialState)) {
            distance = (MOD - distance) % MOD;
        }
        println(distance)
    }
}

fun lexLess(a: List<Int>, b: List<Int>): Boolean {
    for (i in a.indices.reversed()) {
        if (a[i] != b[i]) {
            return a[i] < b[i]
        }
    }
    return false
}

fun readState(): List<Int> {
    val values = readln().split(" ").map { it.toInt() }.toMutableList()
    var reverseDirection = false
    for (i in values.indices.reversed()) {
        if (values[i] == 2) {
            reverseDirection = !reverseDirection
        } else if (reverseDirection) {
            values[i] = 4 - values[i]
        }
    }
    return values
}

fun distFromStart(values: List<Int>): Int {
    var result = 0L
    for (i in values.indices.reversed()) {
        result = (3 * result + (values[i] - 1)) % MOD
    }
    return result.toInt()
}