Hossa (Bull Market)
Time limit1sMemory limit128 MB
Given a hossa permutation, output the next hossa in the defined recursive order.
- Level
Hard8 of 10
- Topics
- Combinatorics, Recursion
- Solved
- No attempts yet
Problem
Consider a sequence of distinct natural numbers. We call this sequence a hossa (a bull market) if for every three positions the following holds: whenever , we have .
Intuitively, if between two days and the price rose from to (that is, ), then on no later day does the price ever fall back to or below.
For example, the 14 hossas made of the elements are:
By contrast, is not a hossa, because the price rose from to and later fell to .
Every hossa can be written as , where is the largest value, is the elements to the left of , and is the elements to the right of . For instance, in the hossa we have , , and . Both and are themselves hossas made of fewer elements.
For two different hossas and built from the same numbers (one is a permutation of the other), we define as follows:
- If has fewer elements than , then .
- If they have the same number of elements, compare whether the hossa is smaller than the hossa (that is, ).
- If and are exactly the same sequence, compare whether .
Sorting the hossas made of by this order gives the list shown above. Some comparisons:
- : by rule 3 it reduces to , which by rule 3 reduces to , which holds by rule 1.
- : by rule 2 it reduces to .
Given a hossa , output its immediate successor : the unique hossa such that
- , and
- for every other hossa with .
You may assume that such an always exists for the given input. For example, the immediate successor of is , the successor of is , and the next one is .
Input
The first line contains an integer (). The second line contains distinct natural numbers, separated by single spaces, each at most ; these are the elements of some hossa .
Output
Print the natural numbers of the immediate successor of the hossa on one line, separated by single spaces.