Tanglegram
On a plane, there are two complete binary trees, each with a depth of N. Their 2x2^N leaves are arranged on two parallel lines and numbered sequentially from left to right. Leaves with the same number in both trees are directly opposite each other. A one-to-one correspondence is established between the leaves of the trees, meaning each leaf in one tree is paired with exactly one leaf in the other tree. In the illustration, these correspondences are depicted by straight line segments connecting the leaves. This setup, consisting of two trees and the correspondences between their leaves, is known as a tanglegram. Tanglegrams are often used by biologists to study the relationships between genes of different plant species.
Tanglegrams become challenging to analyze when many of the correspondence segments intersect. To minimize the number of intersections, a single operation is allowed: in the first (upper) tree, you can swap the two subtrees of any vertex, as illustrated in the second image.
Task
Write a program that, given the information about the correspondences between the leaves of the two trees, calculates the minimum possible number of intersections of segments in the tanglegram's graphical representation. This can be achieved by performing swaps of adjacent subtrees in the first tree. If more than two segments intersect at a single point, the number of intersections should be counted as the number of pairwise intersections of segments. For instance, in the first illustration, the correspondences 4-8, 5-5, and 6-4 result in three intersections.
Input
The first line contains a natural number N (1 ≤ N ≤ 19), representing the depth of the trees. The second line contains 2^N distinct integers ranging from 1 to 2^N. Each i-th integer specifies the leaf of the second tree that is connected by a segment to the i-th leaf of the first tree.
Output
Output the minimum possible number of intersections of correspondence segments in the tanglegram that can be achieved by swapping subtrees in the first tree.