Codeforces Round 1077 (Div. 1)
F2
Al Fine (Counting Version)
Codeforces
3500
原题
← F1G →
翻译中…

This is the counting version of the problem. The difference between the versions is that in this version, you need to find the number of different common trees. Also, the constraint on $n$ in this version is smaller. You can hack only if you solved all versions of this problem.

翻译中…

For Christmas, Tortinita and Arietta each get a Christmas tree. Coincidentally, their trees share the same properties: both have $n+1$ vertices and are rooted at vertex $0$. In their Christmas card to you, each of them appends a DFS order sequence of their tree after their greetings. Recall that a DFS order sequence is generated by the following pseudocode.

翻译中…

dfs_order = []

def dfs(v):
    dfs_order.append(v)
    pick an arbitrary permutation s of children of v
    for child in s:
        dfs(child)

dfs(root)

翻译中…

Let the DFS order sequence of Tortinita's tree be $a_0, a_1, \ldots, a_n$ and that of Arietta's tree be $b_0, b_1, \ldots, b_n$. You observe that $a_0 = b_0 = 0$, and since they are twin sisters, you wonder if they could have the exact same tree. Therefore, you want to find the number of different common trees$^{\text{∗}}$ for both sequences. Since the answer may be very large, you need to output it modulo $998\,244\,353$.

翻译中…

$^{\text{∗}}$Two trees are considered different if there exists a vertex label for which the set of its children's labels is not identical in both trees. In other words, the ordering of children for any given vertex does not matter.

翻译中…

Input

翻译中…

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows.

翻译中…

The first line of each test case contains one integer $n$ ($2 \le n \le \boldsymbol{5000}$).

翻译中…

The second line of each test case contains $n$ integers $a_1, a_2, \cdots, a_n$ ($1 \le a_i \le n$).

翻译中…

The third line of each test case contains $n$ integers $b_1, b_2, \cdots, b_n$ ($1 \le b_i \le n$).

翻译中…

It is guaranteed that neither sequence $a$ nor $b$ contains duplicates.

翻译中…

It is guaranteed that the sum of $n^2$ over all test cases does not exceed $2.5\cdot10^7$.

翻译中…

Output

翻译中…

For each test case, output one integer — the number of different common trees modulo $998\,244\,353$.

翻译中…

Note

翻译中…

In the first test case, the two different trees are tree A and tree B in the figure below. Note that tree B and tree C are the same.

翻译中…

In the second test case, the only common tree is tree B.

翻译中…

image

翻译中…

样例

Input #1
4
2
1 2
1 2
2
1 2
2 1
5
3 5 1 2 4
3 1 5 4 2
5
2 1 4 5 3
2 4 1 5 3
Output #1
2
1
3
7
InputCopy OutputCopy
题目信息
题号
2187F2
时间限制
2 s
内存限制
256 MB
标签
动态规划
树

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。