Number of Topological Orderings of a Directed Tree considering each node as root
Question 1
Find the number of valid topological orderings for each node considering each node as a root of tree in .
- Codeforces Tutorial: https://codeforces.com/blog/entry/75627
- Codechef Long Challenge: https://www.codechef.com/MARCH21A/problems/MAXTOPO - building upon this idea.
Copied from above codeforces blog entry!
I was checking this problem on csacademy, and I came up with the dp combinatorics solution to calculate the number of topological orderings of a directed tree with a fixed root.
First, let me explain this solution. Let's root the tree at node and calculate = size of the subtree rooted at . Let be the number of possible topological orderings of the subtree rooted at . To calculate , let's imagine has only two children: and . We can see quite easily that . That's because any valid topological ordering of the subtree of will begin with itself and then nodes, and because the nodes of 's and 's subtrees are independent, all possible combinations between them are possible. So, we will choose spots of the spots and put in them all the nodes form 's subtree and put on the rest the nodes from 's subtree. Of course, after assigning how we will combine the two subtrees, we can permute the nodes in these spots as long as these permutations are valid; that's why we are multiplying by . What if v has more than two children? We will loop over them and do the same thing accumulatively. The final expression after some reductions looks like this: , where is a child of . Actually we can reduce this further to , where will loop over all nodes in 's subtree.
I felt really unsatisfied after all these reductions because the final expression didn't make sense on its own. But here's a simpler way to think about it without going through all of this.
The number of valid orderings for the whole tree is . Here, represents all possible permutations. Of course, not all of them are valid. For example, the first element of any valid permutation must be (the root), and that's why we are dividing by . More generally, let's go through the subtrees from the largest to the smallest and perform the division. When considering a subtree, the root of that subtree must appear before all the other nodes from the subtree in the permutation. As we are going over the subtrees from the largest to the smallest, all the permutations of the current subtree contribute to the answer. However, not all of them are valid; we want to fix the root of the subtree in the beginning, so we divide by , so that, now, the current subtree is contributing to the answer by a factor of , instead of a factor of (because we are fixing one of the nodes).
I found this way of thinking about it much more insightful than the way with reductions, so I wanted to share it with you.