Editorial for CEOI '16 P5 - Popeala
Submitting an official solution before solving the problem yourself is a bannable offence.
the number of different topological orderings in the subtree of .
By selecting the ordering for each subtree of (where is a child of ), the only remaining part is to merge the orderings. This can be done very easily by using a lot of combinations or applying the number of anagrams. The formula for the number of anagrams is , where is the number of letters and the number of occurrences of letter .
, for each which is a child of . is the number of nodes in the subtree of .
By opening this recursion and dividing all the factorials, we can obtain a formula for the number of topological orderings: , for each which is a node in the tree different from the root.
can be obtained very easily from the helper which is . We just have to divide it by (multiply it with the inverse modular).
The current complexity is . For each query, we loop through all values and divide the answer using inverse modular.
In order to make the program fast, it was necessary to analyze the test cases and observe the fact that the tree is generated randomly. Upon testing, we can deduce that there are not that many different values for , so for each query, we can apply the formula and loop only through all the different values of .
Complexity: , where is a constant for the number of different values of . For , this value is close to .
Comments