Hanoi Towers Reloaded
Time limit2sMemory limit2048 MB
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 disks of diameters . 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 and , and between rods and , but not between rods and .
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 .
Input
The first line contains the number of test cases (). Each test case follows.
The first line of each test case contains an integer (), the number of disks.
The second line contains integers (), where is the rod holding the -th disk. The third line describes the final configuration in the same format.
The sum of over all test cases does not exceed .
Output
For each test case, print the minimum number of moves needed to go from the first configuration to the second, modulo .
Any two configurations can reach each other in this variation.


