Binary Tree
Time limit1sMemory limit1024 MB
For each tree T_i built by joining two earlier trees, sum the fewest subtrees needed to cover each contiguous leaf range exactly.
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Math
- Solved
- No attempts yet
Definitions
For a binary tree in which every node has either or children, is defined as follows.
- In , the subtree rooted at node consists of and the descendants of .
- The inorder sequence of is the sequence of nodes in the order they are visited by an inorder traversal of . It is defined recursively.
- Let be the root of . is the sequence of length that contains only .
- If has children, is .
- If has children, let be the subtree rooted at the left child of and the subtree rooted at the right child of . Then is , , and concatenated in that order.
- Let be the number of leaf nodes of . Number the leaves in the order they appear in , that is, in inorder visiting order.
- Selecting a subtree of covers the leaf nodes contained in it.
- For , is the minimum number of subtrees that must be selected in so that exactly the leaves numbered through are covered and no other leaf is covered.
- is the sum of over all integer pairs with , taken modulo .
The tree in (a) is the tree built from the definition. (b) shows the same tree with its leaves numbered.


is . Selecting the two subtrees shown below covers only leaves , , and .

Summing over all gives . Taking that modulo gives .
Problem
Integer sequences and are given.
Define binary trees as follows.
- is a tree with one node.
- For , is the tree whose left child of the root roots the subtree and whose right child of the root roots the subtree (, ).
Write a program that computes .
Input
The first line contains the integer . Each of the next lines contains and , separated by a space, for from to .
Output
Print lines. On line (), print .
Constraints
- All given numbers are integers.
- ()
- ()