Mars Bacteria Lineup

Time limit1sMemory limit128 MB

Summary
Given a repulsion matrix, choose left/right swap at every node of a complete binary tree to minimize the total sum of adjacent-pair distances in the resulting leaf permutation.
Level

Hard8 of 10

Topics
Dynamic programming, Tree, Divide and conquer, Combinatorics
Solved
No attempts yet

Problem

Scientists discovered unusual bacteria on Mars. The population starts from one bacterium. In each generation, every bacterium splits into two bacteria and the original one disappears. Therefore, generation K+1K+1 contains 2K2^K bacteria.

The scientists numbered the bacteria in the last generation from 1 to 2K2^K. The numbering has the property that the descendants of every ancestor form a consecutive interval of numbers. The descendants of the generation KK bacteria are {1,2}\{1,2\}, {3,4}\{3,4\}, ..., {2K−1,2K}\{2^K-1,2^K\}, and the descendants of the generation K−1K-1 bacteria are consecutive intervals of size 4. In the same way, the descendants of the two generation 2 bacteria are {1,2,…,2K−1}\{1,2,\ldots,2^{K-1}\} and {2K−1+1,…,2K}\{2^{K-1}+1,\ldots,2^K\}.

When the bacteria are rearranged, this property must still hold: for every ancestor bacterium, all of its descendants must occupy one consecutive block in the new order. Equivalently, in the complete binary tree representing the genealogy, each internal node may independently swap the order of its left and right descendant groups.

A repulsion value is given for every pair of bacteria. If two bacteria become adjacent in the new order, the distance between them must be at least their repulsion value. The length of an order is the sum of the distances between every adjacent pair. Find the minimum possible length of an order that satisfies the genealogy condition.

Input

The first line contains a positive integer KK. (1≤K≤9)(1 \le K \le 9)

The next 2K2^K lines contain the repulsion matrix. Each line contains 2K2^K integers, and every value is between 00 and 10610^6, inclusive. The number in row mm and column nn is the repulsion between bacterium mm and bacterium nn. The matrix is symmetric, and the repulsion of a bacterium with itself is 00.

Output

Output the minimum possible length of a valid order.

Examples2

  1. Example 1

    Input
    2
    0 7 2 1
    7 0 4 3
    2 4 0 5
    1 3 5 0
    
    Expected output
    13
    
  2. Example 2

    Input
    3
    0 2 6 3 4 7 1 3
    2 0 7 10 9 1 3 6
    6 7 0 3 5 6 5 5
    3 10 3 0 9 8 9 7
    4 9 5 9 0 9 8 4
    7 1 6 8 9 0 8 7
    1 3 5 9 8 8 0 10
    3 6 5 7 4 7 10 0
    
    Expected output
    32