#P3521. [POI 2011] ROT-Tree Rotations

[POI 2011] ROT-Tree Rotations

Description

You are given a binary tree with nn leaves. Each leaf has a weight pip_i (note: the root is not a leaf), and the weights of all leaves form a permutation of 1n1 \sim n.
For any node in this binary tree, it is guaranteed that it is either a leaf, or it has both left and right children.
You may choose any set of nodes and swap their left and right subtrees.
On the final tree, perform a preorder traversal of the whole tree and record the weights of the encountered leaves to form a permutation of length nn. You need to minimize the number of inversions of this permutation.

Input Format

The first line contains an integer nn, the number of leaves.
In the following lines, the tree is read recursively. When reading any subtree, start with its root. For a node uu, first read an integer xx on a separate line.

  • If x0x \neq 0, then uu is a leaf and its weight is xx.
  • If x=0x = 0, then uu is an internal node; next read the information of its left subtree, and then the information of its right subtree.

Output Format

Output a single integer, the minimal number of inversions.

3
0
0
3
1
2

1

Hint

Explanation for Sample 1:

In the figure below, the left is the initial tree, and the right is the tree after the operations.

Constraints:

  • For 30%30\% of the testdata, n5×103n \leq 5 \times 10^3.
  • For 100%100\% of the testdata, 2n2×1052 \leq n \leq 2 \times 10^5, 0xn0 \leq x \leq n, and the weights of all leaves form a permutation of 1n1 \sim n.

Note: Please note that nn is not the number of nodes in the tree.

Translated by ChatGPT 5