A permutation of order is a sequence p = (p[1], p[2], \ldots, p[n]) in which each number from to occurs exactly once. It is convenient to view a permutation as a mapping that takes the number to the number : i \to p[i].
The inverse of a permutation is the permutation p^{-1} that returns every number to its place: if takes to , then p^{-1} takes back to . In other words, for all the following equality holds:
This equality directly gives the algorithm: the number must be at position of the inverse permutation. Iterate over all from to and perform the assignment pi[p[i]] = i for each of them, where the array stores the inverse permutation.
Each position of the array is filled exactly once. Indeed, the values p[1], p[2], \ldots, p[n] are pairwise distinct and cover all numbers from to , so the indices are also pairwise distinct and cover all positions from to .
Two-line notation. A permutation is often written in two lines: the top line contains the numbers 1, 2, \ldots, n, and under each number stands the value . To obtain the inverse permutation, it is enough to swap the lines and sort the columns in increasing order of the top line.
Example
Consider the permutation from the example. Let us write it and its inverse in two-line notation:
Let us find p^{-1} using the formula pi[p[i]] = i:
We get p^{-1} = (3, 1, 2). Two-line notation gives the same result: swapping the lines of the permutation , we obtain the columns , , . Sorting them by the top line, we get the bottom line .
In the figure, the permutation is shown as arrows i \to p[i]. In the inverse permutation, all arrows point in the opposite direction: p[i] \to i.
Algorithm implementation
The array stores the input permutation, and the array stores the inverse permutation.
#define MAX 20010
int p[MAX], pi[MAX];Read the input permutation.
scanf("%d",&n);
for(i = 1; i <= n; i++)
scanf("%d",&p[i]);Compute the inverse permutation.
for(i = 1; i <= n; i++)
pi[p[i]] = i;Print the inverse permutation.
for(i = 1; i <= n; i++)
printf("%d ",pi[i]);
printf("\n");Python implementation
The list stores the input permutation, and the list stores the inverse permutation. Read the input data.
n = int(input())
p = [0] + list(map(int, input().split()))
pi = [0] * (n + 1)Compute the inverse permutation.
for i in range(1, n + 1):
pi[p[i]] = iPrint the inverse permutation.
for i in range(1, n + 1):
print(pi[i], end=" ")
print()