Tree Rotations

No attempts yetTime limit1sMemory limit128 MB

Problem

Byteasar the gardener grows a rare tree called Rotatus Informatikus. It has a few notable properties:

  • The tree is built from straight branches, bifurcations, and leaves. The trunk rising from the ground counts as a branch too.
  • Each branch ends at its top in either a bifurcation or a leaf.
  • Exactly two branches fork out of every bifurcation: a left branch and a right branch.
  • Each leaf carries a distinct integer label from 11 to nn.
  • A rotation may be applied to any bifurcation, swapping the left and right branches that fork out of it.

The corona of the tree is the sequence of integers read off the leaf labels from left to right.

Rotatus Informatikus

The tree on the left has corona 3,1,23, 1, 2 and two inversions. A single rotation yields the tree on the right, whose corona 1,3,21, 3, 2 has just one inversion. Both trees have five branches.

The neatness of a tree is the number of inversions in its corona, that is, the number of pairs (i,j)(i, j) with 1i<jn1 \le i < j \le n and ai>aja_i > a_j in the corona a1,a2,,ana_1, a_2, \dots, a_n.

Compute the minimum number of inversions in the corona that can be reached by a sequence of rotations.

Input

The first line contains a single integer nn (2n2000002 \le n \le 200000), the number of leaves. The description of the tree follows and is defined recursively:

  • if the trunk ends in a leaf labelled pp (1pn1 \le p \le n), the description is a single line holding the integer pp;
  • if the trunk ends in a bifurcation, the description has three parts: a line holding the single number 00, then the description of the left subtree (treating the left branch as its trunk), then the description of the right subtree (treating the right branch as its trunk).

Output

Print one integer: the minimum number of inversions in the corona attainable by a sequence of rotations.

Hint

The figure above shows the tree with corona 3,1,23, 1, 2, which has two inversions; a single rotation gives corona 1,3,21, 3, 2 with one inversion, the minimum.