Superpermutations
Time limit1sMemory limit512 MB
Given a permutation of 1 to n, find the position where it starts in the superpermutation s_n built by Dima's insertion process, modulo 1e9+7.
- Level
Hard8 of 10
- Topics
- Combinatorics, Math, Implementation
- Solved
- No attempts yet
Superpermutations
Once, during his informatics class, Dima solved all the problems about permutations. Then he came up with a problem about a superpermutation.
A superpermutation of order is a sequence of integers from to such that every permutation of the numbers from to occurs as a contiguous subsegment of the sequence.
Dima came up with the following algorithm for generating superpermutations:
- .
- Set equal to at first.
- Consider all subsegments of of length , from left to right, in order of increasing start position.
- If the current subsegment is a permutation of the numbers from to (each number from to occurs exactly once), insert the numbers into right after the last element of that subsegment.
Here is how the superpermutations of order , , and are built.
By definition, .
Set . The only subsegment of length is , which is a permutation, so we insert after it. The result is .
Set . The subsegment is a permutation, so we insert after it, giving . The subsegment is also a permutation, so we insert after it. The result is .
Set . The subsegments of length that are permutations are, in order, , , and . We insert , , and after them, respectively. The subsegments is not a permutation, so nothing happens there. The remaining two permutations, and , are handled the same way.
Dima noticed that this method builds a superpermutation in which every permutation occurs exactly once. To check his work, he wants to find the position where a given permutation occurs in his superpermutation . Positions start at 1.
Since is extremely long, output the index of the first element of where the occurrence starts, modulo .
Input
The first line contains a single integer , the length of the permutation ().
The second line contains integers , the given permutation (, all are distinct).
Output
Output a single integer, the position where the permutation occurs in the superpermutation of order , modulo .