Under construction

Still being built. Things may change

Addition palindrome sequences and trees

Time limit1sMemory limit1024 MB

Summary
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.

  1. Choose two adjacent numbers in the sequence.
  2. Remove the two chosen numbers, and insert their sum at the position where they were removed.
  3. Repeat steps 1 and 2 as many times as you want. (You do not have to repeat them.)
  4. 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, [11,12,13,12,11][11,12,13,12,11] and [11,12,12,11][11,12,12,11] are palindrome sequences, but [1,11,111][1,11,111] and [1,12,21,1][1,12,21,1] are not.

[1,1,3,5,3,2][1,1,3,5,3,2] is an addition palindrome sequence because it can be turned into [2,3,5,3,2][2,3,5,3,2]. [1,2,5,2][1,2,5,2] 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 (1,2)(1,2) and (2,1)(2,1) 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 33.

If you choose the leaf pair below, the simple path is [1,2,1][1,2,1]. 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 [1,2,1,2,1][1,2,1,2,1]. It is already a palindrome, so it is an addition palindrome sequence.

If you choose the leaf pair below, the simple path is [1,2,2][1,2,2]. 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 hh of the tree. (2≤h≤10)(2\le h\le 10)

The second line contains A1,A2,⋯ ,A2h−1A_1, A_2, \cdots, A_{2^h-1}, separated by spaces. (−1 000≤Ai≤1 000)(-1\,000\le A_i\le 1\,000)

AiA_i is the value written on node ii.

The root is always node 11, and the parent of node ii (i≥2i\ge 2) is ⌊i/2⌋\lfloor i/2 \rfloor.

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.

Examples1

  1. Example 1

    Input
    3
    1 2 2 1 1 1 2
    
    Expected output
    5