This page is still under construction.

Parts of this page are still being built. What you see may change.

Binary Tree Lexicographic Number

Time limit1sMemory limit128 MB

Summary
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 00, 11, or 22 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 00.

A lexicographic order is defined on binary trees. Tree AA is lexicographically smaller than tree BB when one of the following holds:

  • the height of AA is smaller than the height of BB, or
  • AA and BB have the same height and:
    • the left subtree of AA is lexicographically smaller than the left subtree of BB, or
    • the left subtrees of AA and BB are equal and the right subtree of AA is lexicographically smaller than the right subtree of BB.

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 AA and BB are different and AA is not lexicographically smaller than BB, then AA is lexicographically larger than BB.

Number every binary tree according to this order. The tree that consists of a single vertex has number 11. For the given tree, output its number modulo 1 000 000 0001\,000\,000\,000.

Input

The first line contains the number of trees tt (1≤t≤1 0001 \le t \le 1\,000).

Then tt tree descriptions follow. The first line of each description contains the number of vertices nn (1≤n≤2 0001 \le n \le 2\,000). The vertices are numbered from 11 to nn, and vertex 11 is the root.

The next nn lines describe the children. The ii-th of them contains two integers lil_i and rir_i, the indices of the left and right child of vertex ii. If vertex ii has no left child then li=−1l_i = -1, and if it has no right child then ri=−1r_i = -1.

Output

Print exactly tt lines. The ii-th line contains the number of the ii-th tree in the order defined above, taken modulo 1 000 000 0001\,000\,000\,000.

Examples1

  1. Example 1

    Input
    4
    1
    -1 -1
    2
    -1 2
    -1 -1
    2
    2 -1
    -1 -1
    3
    2 3
    -1 -1
    -1 -1
    
    Expected output
    1
    2
    3
    4