Next 3-1-2 pattern avoiding permutation
Time limit0.1sMemory limit32 MB
Given a 3-1-2-avoiding permutation of 1 to n, print the next one in lexicographic order.
- Level
Hard8 of 10
- Topics
- Combinatorics, Greedy, Implementation
- Solved
- No attempts yet
Problem
Pattern avoidance in permutations is a long studied topic in combinatorics and computer science. A permutation of the natural numbers avoids the 3-1-2 pattern if there are no indices with , and .
List every permutation of that avoids the 3-1-2 pattern in lexicographic order. Given one permutation from that list, compute the permutation that follows it. The decreasing sequence is the last entry of the list, and the input is never that permutation, so the answer always exists.
Input
The first line contains an integer (). The second line contains a permutation of as integers separated by single spaces. The permutation avoids the 3-1-2 pattern and is not the decreasing sequence .
Output
Print on the first line the permutation that follows the input permutation in the lexicographic order of all 3-1-2 pattern avoiding permutations. Separate the numbers with single spaces.