Permutations
InterviewTime limit2sMemory limit1024 MB
Given an inversion table of a permutation, output the permutation's cycle notation with each cycle starting from its smallest element.
- Level
Medium5 of 10
- Topics
- Array, Binary search, Implementation
- Solved
- No attempts yet
Problem
Let denote the set . A permutation of order is a one-to-one mapping from the set to the set . For example, let be a concrete permutation of order . We usually represent it with a table like this:
This means that , , , and so on. Since the top row is always , we usually omit it and write the permutation in the one-line notation:
The cycle notation is also very popular. We start with element and determine its image . Next, we take the element and determine its image . We keep doing this until we arrive back at the element . Indeed, . The permutation contains the cycle . Then we take the smallest number that has not yet appeared in any cycle, which is in this case, and repeat the process. Eventually, we obtain the following:
A permutation of order can also be represented by an inversion table (), where is the number of elements that are greater than and appear to the left of in the one-line notation. In our example, the inversion table is:
Every permutation can be written in exactly one way as an inversion table, and every inversion table with for all represents a valid permutation.
Write a program that converts an inversion table to its corresponding cycle notation.
Input
The first line contains an integer , the order of a permutation. The second line contains space-separated integers describing a valid inversion table.
Output
Output one line that contains the cycle notation of the permutation given by the inversion table. Each cycle is enclosed in parentheses. Cycles are separated by one space. The numbers within a cycle are separated by one space. The smallest element always comes first in each cycle. Cycles are ordered by their first element. See the examples.