
Two ways of conquering the world are considered different if the order in which the king conquered the kingdoms from 1 to N-1 are different. Refer to the example below for a better understanding.
If N = 4, prevKingdom = { -1, 0, 0, 1 } , then the network of kingdoms is denoted as:

Then the King has 3 ways to conquer the world:
0 -> 1 -> 2 -> 3
0 -> 1 -> 3 -> 2
0 -> 2 -> 1 -> 3
All these 3 ways satisfy the constraint that before conquering any kingdom all the kingdoms on the shortest path to the 0th kingdom have been conquered, in other words: before conquering kingdom-3 the King must conquer kingdom-1.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains a single integer ‘N’ denoting the number of kingdoms.
The next line contains N integers, ‘prevKingdom[i]’ denoting that the ith kingdom can only be reached from the prevKingdom[i]^th kingdom.
For each test case, print a single integer denoting the number of ways the King can conquer the world.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
0 <= N <= 10000
0 <= prevKingdom[i] < N, and prevKingdom[0] = -1
Time limit: 1 sec
This problem simply wants us to find the number of topological orderings of a directed tree rooted at 0.
Consider a case :
Where we have already precalculated answers for the subtree rooted at nodes 1 and 2.
After understanding this logic the question can simply be tackled by the dfs-algorithm.
Do note that some languages might require you to do inverse modulo calculations. Using Fermat's little theorem we can directly calculate the value of ( (a*b-1) % p ) as:
The steps are as follows :