Infinite Binary Embedding
Time limit2sMemory limit256 MB
Count the ways to embed a finite binary tree into the infinite binary tree so that each leaf lands at a prescribed height, modulo 1e9+7.
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Combinatorics, Math
- Solved
- No attempts yet
Problem
Vasya has an infinite binary tree , which can be formally described as follows. has infinitely many vertices, numbered starting from 1. Each vertex of has two children: a left son and a right son. The left son of vertex is vertex , and the right son of vertex is vertex .
Vasya also has another binary tree (a finite one, fortunately). Every vertex of is either an internal vertex or a leaf. An internal vertex has a left son and a right son (and is called the parent of its children), and a leaf vertex has no children. Each vertex has exactly one parent, except for one vertex with no parent; this vertex is called the root of tree .
Vasya wants to embed tree in the infinite tree . Formally, an embedding is a function (here is the set of vertices of tree ) with the following property: if vertex is a left (alternatively: right) son of vertex in , then vertex must lie in the subtree of the left (alternatively: right) son of vertex in .
Informally, an embedding is a way to place the vertices of somewhere on so that if we draw paths between all the embedded vertices and their children, the drawing looks like with some of the edges possibly extended downward (looking at the pictures for the sample cases might help to understand the notion better).
Additionally, for each leaf vertex Vasya has chosen a number , the height of the vertex of that should be embedded to (the height of a vertex is the number of edges between the vertex and the root of the tree). That is, must hold for every leaf of tree .
Now Vasya wants to know the number of different embeddings of in such that each leaf is embedded to a vertex with height . As the number may be quite large, find it modulo .
Input
The first line contains one integer , the number of vertices of ().
The next lines describe the tree and the numbers .
If the -th vertex is an internal vertex, then the first number in the -th line is , followed by the numbers of its left and right sons respectively.
If the -th vertex is a leaf, then the first number in the -th line is , followed by the number for this leaf. All satisfy .
The root of is vertex .
Output
Print one integer: the number of appropriate embeddings modulo .
Notes
All six possible embeddings for the first sample (note that the root of does not have to coincide with the root of ):

All fourteen possible embeddings for the second sample:
