问题 F: Doremy's Starch Trees

内存限制:1024 MB 时间限制:6 S
题面:Markdown 评测方式:Special Judge 上传者:
提交:5 通过:0

题目描述

A rooted tree $T_2$ is called to be a unrooted tree $T_1$'s starch tree if and only if these two conditions are satisfied at the same time (Denote that $s_i$ is the set of all vertices in the $i$'s subtree **on tree** $T_2$): 1. $T_1$ and $T_2$ have the same number of vertices; 2. for any vertices $x$ that have child, and for any $x$'s child $y$, there is at least one vertex $z\in s_y$ connected to $x$ **on tree** $T_1$. Now Doremy has a unrooted tree $X$, and she remembers that a rooted tree $Y$ is $X$'s starch tree. However, Doremy forgets the root of $Y$. Can you help Doremy find the root or claim that there is no possible root?

输入格式

The input consists of multiple test cases. The first line contains a single integer $t$ ($1\le t\le 10^5$) - the number of test cases. The description of the test cases follows. The first line contains one integer $n$ ($2 \le n \le 10^6$), the number of vertex in the tree. The second line contains $n-1$ integers $a_2,\cdots,a_n$, indicating that there is an edge $(i,a_i)$ on tree $X$. It is guaranteed that they form a tree. The third line contains $n-1$ integers $b_2,\cdots,b_n$, indicating that there is an edge $(i,b_i)$ on tree $Y$. It is guaranteed that they form a tree. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^6$.

输出格式

For each test case, output $-1$ if $Y$ is not a starch tree of $X$. Otherwise, output a possible root $r$ ($1 \le r \le n$). If there are multiple answers, output any.

输入样例 复制

13
5
1 1 2 2
1 5 2 2
10
1 2 1 4 5 6 7 8 9
3 1 5 1 7 5 7 8 9
4
1 2 3
1 1 1
5
1 2 1 1
1 4 1 1
4
1 2 3
1 2 2
11
1 2 3 1 5 6 1 8 1 10
3 1 1 6 1 10 1 8 8 10
10
1 2 3 4 4 3 7 3 9
4 2 1 1 4 8 3 10 3
2
1
1
6
5 2 5 1 3
3 6 3 4 1
5
1 1 1 1
1 4 5 2
7
1 1 2 2 3 3
1 2 3 2 3 3
5
1 2 3 4
4 1 5 1
15
4 13 6 6 1 13 6 7 2 10 7 1 7 4
4 5 6 7 1 1 6 7 2 10 3 1 7 4

输出样例 复制

3
1
-1
3
4
-1
5
1
-1
3
4
-1
12

数据范围与提示

The following graph shows the first six test cases. Black edges belong to tree $X$, and red edges belong to tree $Y$. ![](https://uploadfiles.nowcoder.com/images/20240627/0_1719484251825/4F179790A6AF46C92EC7879C636556D3)