Binary Tree Lexicographic Number
Time limit1sMemory limit128 MB
Given binary trees with ordered left and right children, find each tree's rank in height-first lexicographic order modulo 1000000000.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Tree, Combinatorics, Math
- Solved
- No attempts yet
Problem
Call a rooted tree a binary tree if every vertex has , , or children and, whenever a vertex has a child, that child is designated as either its left child or its right child. A vertex with a single child is therefore a different tree depending on whether that child is the left one or the right one.
The height of a tree is the number of vertices on the longest path from the root to a leaf. The empty tree has height .
A lexicographic order is defined on binary trees. Tree is lexicographically smaller than tree when one of the following holds:
- the height of is smaller than the height of , or
- and have the same height and:
- the left subtree of is lexicographically smaller than the left subtree of , or
- the left subtrees of and are equal and the right subtree of is lexicographically smaller than the right subtree of .
If a vertex has no left child, its left subtree is the empty tree; the same applies when it has no right child.
If two trees and are different and is not lexicographically smaller than , then is lexicographically larger than .
Number every binary tree according to this order. The tree that consists of a single vertex has number . For the given tree, output its number modulo .
Input
The first line contains the number of trees ().
Then tree descriptions follow. The first line of each description contains the number of vertices (). The vertices are numbered from to , and vertex is the root.
The next lines describe the children. The -th of them contains two integers and , the indices of the left and right child of vertex . If vertex has no left child then , and if it has no right child then .
Output
Print exactly lines. The -th line contains the number of the -th tree in the order defined above, taken modulo .