atcoder#ABC276C. [ABC276C] Previous Permutation

[ABC276C] Previous Permutation

Score : 300300 points

Problem Statement

You are given a permutation P=(P1,,PN)P = (P_1, \dots, P_N) of (1,,N)(1, \dots, N), where (P1,,PN)(1,,N)(P_1, \dots, P_N) \neq (1, \dots, N).

Assume that PP is the KK-th lexicographically smallest among all permutations of (1,N)(1 \dots, N). Find the (K1)(K-1)-th lexicographically smallest permutation.

What are permutations?

A permutation of (1,,N)(1, \dots, N) is an arrangement of (1,,N)(1, \dots, N) into a sequence.

What is lexicographical order?

For sequences of length NN, A=(A1,,AN)A = (A_1, \dots, A_N) and B=(B1,,BN)B = (B_1, \dots, B_N), AA is said to be strictly lexicographically smaller than BB if and only if there is an integer 1iN1 \leq i \leq N that satisfies both of the following.

  • (A1,,Ai1)=(B1,,Bi1).(A_{1},\ldots,A_{i-1}) = (B_1,\ldots,B_{i-1}).
  • Ai<BiA_i < B_i.

Constraints

  • 2N1002 \leq N \leq 100
  • 1PiN(1iN)1 \leq P_i \leq N \, (1 \leq i \leq N)
  • PiPj(ij)P_i \neq P_j \, (i \neq j)
  • (P1,,PN)(1,,N)(P_1, \dots, P_N) \neq (1, \dots, N)
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

NN

P1P_1 \ldots PNP_N

Output

Let Q=(Q1,,QN)Q = (Q_1, \dots, Q_N) be the sought permutation. Print Q1,,QNQ_1, \dots, Q_N in a single line in this order, separated by spaces.

3
3 1 2
2 3 1

Here are the permutations of (1,2,3)(1, 2, 3) in ascending lexicographical order.

  • (1,2,3)(1, 2, 3)
  • (1,3,2)(1, 3, 2)
  • (2,1,3)(2, 1, 3)
  • (2,3,1)(2, 3, 1)
  • (3,1,2)(3, 1, 2)
  • (3,2,1)(3, 2, 1)

Therefore, P=(3,1,2)P = (3, 1, 2) is the fifth smallest, so the sought permutation, which is the fourth smallest (51=4)(5 - 1 = 4), is (2,3,1)(2, 3, 1).

10
9 8 6 5 10 3 1 2 4 7
9 8 6 5 10 2 7 4 3 1