Under construction

Still being built. Things may change

Hanoi Towers Reloaded

Time limit2sMemory limit2048 MB

Summary
Given two disk configurations on three rods, find the minimum number of moves between adjacent rods to turn the first into the second, modulo 998244353.
Level

Medium7 of 10

Topics
Recursion, Math, Implementation
Solved
No attempts yet

Problem

The Towers of Hanoi is a famous mathematical puzzle with three rods and nn disks of diameters 1,2,…,n1, 2, \ldots, n. Each rod holds some disks stacked in decreasing order of diameter from bottom to top, so the smallest disk is always on top. A valid move takes the smallest disk from a rod and places it on top of another rod. The order must stay sorted, so you cannot put a larger disk onto a smaller one. The original goal is to move all disks from one rod to another.

In this variation, you can only move disks between adjacent rods. You can move a disk between rods 11 and 22, and between rods 22 and 33, but not between rods 11 and 33.

Valid moveInvalid move: non-adjacent rodsInvalid move: moving a larger disk onto a smaller one

Given two configurations of this puzzle, find the minimum number of moves needed to go from the first configuration to the second. The answer can be large, so print it modulo 998 244 353998\,244\,353.

Input

The first line contains the number of test cases tt (1≤t≤1031 \le t \le 10^3). Each test case follows.

The first line of each test case contains an integer nn (1≤n≤1051 \le n \le 10^5), the number of disks.

The second line contains nn integers x_1,x_2,…,x_nx\_1, x\_2, \ldots, x\_n (x_i∈{1,2,3}x\_i \in \{ 1, 2, 3 \}), where x_ix\_i is the rod holding the ii-th disk. The third line describes the final configuration in the same format.

The sum of nn over all test cases does not exceed 10510^5.

Output

For each test case, print the minimum number of moves needed to go from the first configuration to the second, modulo 998 244 353998\,244\,353.

Any two configurations can reach each other in this variation.

Examples1

  1. Example 1

    Input
    4
    1
    1
    3
    2
    3 3
    2 1
    3
    3 2 1
    1 2 3
    4
    2 1 3 2
    2 1 3 2
    
    Expected output
    2
    7
    20
    0