Lexical
InterviewTime limit2sMemory limit1024 MB
Given n and a permutation of 0 to n-1, compute its 1-based position in lexicographic order.
- Level
Medium4 of 10
- Topics
- Combinatorics, Math
- Solved
- No attempts yet
Problem
A permutation of a set is a sequence in which every element of the set occurs exactly once. For example, the sequence 3201 is a permutation of the set , where 3 comes first, 2 comes second, 0 comes third and 1 comes last.
Permutations can be ordered in a lexicon by looking at the first position where two of them differ. The one with the smaller number at that position comes first. So 3201 comes before 3210: at the third position, which is the first position where they differ, one has a 0 and the other has the bigger number 1.
For the lexicon holds 24 entries and runs like this.
0123, 0132, 0213, 0231, 0312, 0321, 1023, 1032, 1203, …, 3201, 3210
Given an integer () and a permutation of the set , determine the position of that permutation in the lexicon.
Hint: the lexicon has entries, so building all of it is too slow once is close to 13.
Input
The input consists of two lines.
The first line contains the integer .
The second line contains a permutation of the set , with the numbers separated by a space.
Output
Print a single integer, the position of the permutation in the lexicon. Positions are counted from 1, so the first permutation is at position 1.