Grandfather Gepetto's family is very large, consisting of himself and of his descendants (children, grandchildren, great-grandchildren, great-great-great-grandchildren, etc.).
Since Gepetto cannot remember the names of all the members of his family, he has assigned each of them (including himself) a unique number between and .
Moreover, since Gepetto doesn't get along well with his relatives by marriage, he only remembers, for each person, who their parent is, that parent also being a descendant of Gepetto. For each , let be the number associated with the parent of person . We consider the number associated with Gepetto's parent to be .
On Children's Day, Gepetto wants to give each member of his family (including himself) a gift, but he is torn over the order in which to give out the gifts. An order of giving out the gifts can be represented as a permutation , meaning that:
- Gepetto will give the first gift to the person numbered ;
- Gepetto will give the second gift to the person numbered ;
- Gepetto will give the last gift to the person numbered .
Gepetto considers a gift-giving order to be good if every person in the family receives their gift earlier than all of their children.
After choosing a good gift-giving order , Gepetto nevertheless wonders what position this order would occupy in the lexicographically sorted sequence of all good gift-giving orders.
Since this position can be very large, Gepetto is satisfied with just its remainder modulo .
An order is lexicographically smaller than another order if there exists a position () such that:
- , for all indices satisfying ;
- .
Implementation Details
You must implement the function
int solve(int N, std::vector<int> P, std::vector<int> V)
which receives as parameters:
- , the number of family members.
- , a vector indexed from where represents the parent of person , for every .
- , a permutation of the numbers , representing the gift-giving order chosen by Gepetto.
The function must return a single integer, representing the index of the permutation in the lexicographically sorted sequence, modulo .
Constraints and Notes
- It is guaranteed that there exists exactly one for which . This is the number associated with Gepetto.
- It is guaranteed that the graph formed by all the edges is a tree (an acyclic undirected graph).
- It is guaranteed that each number from to appears exactly once in the sequence . In other words, it is guaranteed that the sequence is a permutation of order .
| # | Score | Constraints |
|---|---|---|
| 1 | 7 | |
| 2 | 16 | |
| 3 | 22 | |
| 4 | 11 | There exists a node with children |
| 5 | 27 | |
| 6 | 17 | No additional restrictions. |
Example 1
input
6
3 3 0 3 3 3
3 4 6 1 2 5
output
67
Explanation
The family tree from the first example:

Example 2
input
10
4 9 9 0 1 4 9 4 4 8
4 6 1 8 5 10 9 3 7 2
output
5158
Explanation
The family tree from the second example:
