Hanoi Towers Reloaded

시간 제한2초메모리 제한2048 MB

요약
디스크를 인접한 막대 사이에서만 옮길 수 있는 하노이 퍼즐에서 두 배치가 주어질 때, 최소 이동 횟수를 998244353으로 나눈 나머지를 구한다.
난이도

어려움10점 중 8점

유형
재귀, 분할 정복, 수학, 구현
정답자
아직 제출이 없습니다

문제

The Towers of Hanoi is a famous mathematical puzzle consisting of three rods and nn disks with diameters 1,2,…,n1, 2, \ldots, n. Each of the three rods contains some disks, stacked in order of decreasing diameter from bottom to top, so that the smallest disk is always at the top. A valid move consists of taking the smallest disk from a rod and putting it on top of another rod. This move must preserve the sorted order: you can't put a larger disk onto a smaller one. The original puzzle's goal is to transfer all disks from one rod to another.

In this variation of the puzzle, you can only move the 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 required to reach the second configuration starting from the first one. As this number might be large, print it modulo 998,244,353998\\,244\\,353.

입력

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

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

The second line contains nn integers x_1,x_2,…,x_nx\_1, x\_2, \ldots, x\_n, describing the initial configuration of the puzzle, where x_ix\_i is the rod that contains the ii-th disk (x_i∈1,2,3x\_i \in \\{ 1, 2, 3 \\}).

The third line describes the final configuration of the puzzle in the same format.

It is guaranteed that the sum of nn over all test cases does not exceed 10510^5.

출력

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

It can be shown that any two configurations are reachable from each other in this variation of the puzzle.

예제1

  1. 예제 1

    입력
    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
    
    예상 출력
    2
    7
    20
    0