Addition palindrome sequences and trees
Time limit1sMemory limit1024 MB
Count the leaf-to-leaf paths in a full binary tree whose values can be merged by adding adjacent pairs into a palindrome of length 2 or more.
- Level
Medium5 of 10
- Topics
- Tree, DFS, Prefix sum
- Solved
- No attempts yet
Problem
Gunmo was playing with sequences and palindromes when he developed addition palindrome sequences.
A sequence is an addition palindrome sequence if it satisfies the following conditions.
- Choose two adjacent numbers in the sequence.
- Remove the two chosen numbers, and insert their sum at the position where they were removed.
- Repeat steps 1 and 2 as many times as you want. (You do not have to repeat them.)
- If the final sequence is a palindrome of length 2 or more, the initial sequence is an addition palindrome sequence.
A palindrome sequence reads the same forward and backward. For example, and are palindrome sequences, but and are not.
is an addition palindrome sequence because it can be turned into . is not, because no sequence of operations turns it into a palindrome of length 2 or more.
Gunmo thought addition palindrome sequences were too easy. So he wants to count how many simple paths between pairs of leaf nodes in a full binary tree form addition palindrome sequences. The pairs and are the same pair, so count each one once.
A full binary tree is a binary tree where every node has 0 or 2 children, and every leaf is at the same depth. In other words, every leaf is the same distance from the root.
The figure below shows a full binary tree of height .

If you choose the leaf pair below, the simple path is . It is already a palindrome without any addition, so it is an addition palindrome sequence.

If you choose the leaf pair below, the simple path is . It is already a palindrome, so it is an addition palindrome sequence.

If you choose the leaf pair below, the simple path is . No sequence of operations turns it into a palindrome of length 2 or more, so it is not an addition palindrome sequence.

Input
The first line contains the height of the tree.
The second line contains , separated by spaces.
is the value written on node .
The root is always node , and the parent of node () is .
All values in the input are integers.
Output
On the first line, print the number of simple paths between pairs of leaf nodes that form addition palindrome sequences.