Tree Rotations
Time limit1sMemory limit128 MB
Given a binary tree with distinct leaf labels, find the minimum number of inversions in the left-to-right leaf sequence reachable by swapping children at branchings.
- Level
Medium7 of 10
- Topics
- Divide and conquer, Dynamic programming, Tree, Sorting
- Solved
- No attempts yet
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 to .
- 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.

The tree on the left has corona and two inversions. A single rotation yields the tree on the right, whose corona 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 with and in the corona .
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 (), the number of leaves. The description of the tree follows and is defined recursively:
- if the trunk ends in a leaf labelled (), the description is a single line holding the integer ;
- if the trunk ends in a bifurcation, the description has three parts: a line holding the single number , 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 , which has two inversions; a single rotation gives corona with one inversion, the minimum.