QOJ.ac

QOJ

Time Limit: 6 s Memory Limit: 1024 MB Total points: 100

#5017. Equal Tree Chains

Statistics

Given two trees $T_1$ and $T_2$ with the same vertex set $\{1, 2, \dots, n\}$, find the number of non-empty subsets of vertices that form a path in both $T_1$ and $T_2$.

A subset of vertices $S$ forms a path in $T_i$ if and only if there exist $1 \le x \le y \le n$ such that the set of vertices on the shortest path between $x$ and $y$ in $T_i$ is exactly $S$.

Input

The first line contains an integer $n$.

The next two lines each contain $n-1$ integers. Assuming the root of both $T_1$ and $T_2$ is $1$, the $j$-th integer in the $i$-th line represents the parent of node $j+1$ in tree $T_i$.

Output

Output a single integer representing the answer.

Examples

Input 1

7
7 1 3 1 7 1
3 5 3 1 5 3

Output 1

11

Note 1

The valid subsets $S$ are $\{1\}, \{2\}, \{3\}, \{4\}, \{5\}, \{6\}, \{7\}, \{1, 5\}, \{3, 4\}, \{1, 3, 5\}, \{1, 3, 4, 5\}$.

Additional Examples

The provided files contain $10^4$ test cases with $n=10$ in ex_tree1.in/out.

Constraints

For all data, $1 \le n \le 2 \times 10^5, 1 \le p_{i,j} \le n$.

Subtask #1 (10 points): $n \le 5\,000$.

Subtask #2 (20 points): The degree of every node in $T_1$ and $T_2$ is at most $2$.

Subtask #3 (30 points): The degree of every node in $T_1$ and $T_2$ is at most $3$.

Subtask #4 (40 points): No special properties.

Editorials

IDTypeStatusTitlePosted ByLast UpdatedActions
EditorialOpen Official EditorialQingyu- Download

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.