公式

C - Inverse of Permutation 解説 by en_translator


As defined in this problem, given a permutation \(P = (p_1, p_2,\dots, p_N)\), the permutation \(Q = (q_1, q_2, \dots,q_N)\) satisfying \(q_{p_i} = i\) is called its inverse permutation.

In fact, there are many algorithms that utilizes inverse permutations. For example, given a permutation \(P\), suppose that you are given many queries asking “find the position of \(i\) in \(P\).” While searching for \(i\) in \(P\) one by one from its first element takes \(O(N)\) time, if its inverse permutation is precomputed, the answer is \(q_i\), so the query can be processed in an \(\mathrm{O}(1)\) time.

Implementation is quite simple once you figured out. For \(1 \leq i \leq N\), assign Q[P[i]] = i.
It is a little bit unintuitive, as \(Q\) is not filled in the increasing order of its position; however, this procedure is justified because this algorithm fills \(Q_i\) for all possible \(i\) \((1 \leq i \leq N)\), corresponding to each element of \(P\).

Another way to get AC for this problem is to use a data structure like associated array.

Sample codes in C++ and Python follow.

  • C++
#include <iostream>
#include <vector>
using namespace std;

#define rep(i, n) for (int i = 0; i < (n); i++)

int main() {
  int N;
  cin >> N;
  vector<int> p(N), q(N);
  for (auto& x : p) cin >> x, --x;
  rep(i, N) q[p[i]] = i;
  rep(i, N) cout << q[i] + 1 << " \n"[i == N - 1];
}
  • Python
N = int(input())
P = [0] + list(map(int, input().split()))
Q = [-1] * (N + 1)
for i in range(1, N + 1):
  Q[P[i]] = i
print(" ".join(map(str, Q[1:])))

投稿日時:
最終更新: