Bunny Hops Problem Code: BNYHOP Codechef Solutions
Bunny Hops Problem Code: BNYHOPSubmit
Read problem statements in Mandarin, Bengali, Russian, and Vietnamese as well.
Bugs Bunny is very smart, but he keeps constantly worrying about the future and is always anxious. Therefore, he keeps hopping between towns without standing still.
The place where Bugs Bunny lives has towns (numbered through ) with one-way roads connecting them in such a way that they form an arborescence (a tree with all paths directed from the root), rooted at town . Therefore, each town except the root has exactly one incoming road; for each (), there is a road from town to town . Each town has a distinct rating associated with it; for each valid , the -th town has rating .
From a town , Bugs Bunny is allowed to hop to town (without visiting any other towns in between), if the following conditions are satisfied:
- there is a path between towns and , i.e. a path from town to town or from town to town
- town has a lower rating than town , i.e.
This way, Bugs Bunny can visit a sequence of towns by hopping, starting anywhere and stopping whenever he chooses. Clearly, he cannot keep hopping forever, so the number of such sequences is finite.
Tell Bugs Bunny the number of sequences of two or more towns which can be formed by hopping, given that he can start at any town and stop at any town. Since this number can be very large, calculate it modulo .
Input Format
- The first line of the input contains a single integer denoting the number of test cases. The description of test cases follows.
- The first line of each test case contains a single integer .
- The second line contains space-separated integers .
- The third line contains space-separated integers .
Output Format
For each test case, print a single line containing one integer --- the number of valid sequences of visited towns modulo .
Constraints
- for each valid
- are pairwise distinct
- the graph described on the input is a directed tree
- the sum of over all test cases does not exceed
Subtasks
Subtask #1 (20 points): the tree is a straight line --- there is a single path starting at town and passing through all towns
Subtask #2 (20 points):
- the sum of over all test cases does not exceed
Subtask #3 (60 points): original constraints
Sample Input 1
3
3
1 1
10 15 5
5
1 1 3 3
50 10 20 40 30
9
1 1 2 2 2 2 7 7
1 2 3 4 5 6 7 8 9
Sample Output 1
3
8
28
Explanation
Example case 1: The possible hops for Bugs Bunny are from town to town and from town to town . Therefore, the possible sequences of visited towns are , and .
Comments
Post a Comment