#P3832. [SHOI2012] 排序

[SHOI2012] 排序

Description

As is well known, the set of all permutations of {1,2,,n}\{1, 2, \dots, n\} contains n!n! permutations. Normally, when we generate all permutations, we list them in lexicographic order. In this problem, we consider a special way of generating all permutations.

Specifically, the generation order is determined by a generator.

(1) The generator is itself a permutation of {1,2,,n}\{1, 2, \dots, n\}: a1a_1, a2a_2, …, ana_n.

(2) For two distinct permutations of {1,2,,n}\{1, 2, \dots, n\}, x1x_1, x2x_2, …, xnx_n and y1y_1, y2y_2, …, yny_n, first find the smallest ii such that xaix_{a_i} and yaiy_{a_i} are not equal.

(3) According to the ii chosen in (2), if xaix_{a_i} comes before yaiy_{a_i} in the permutation a1a_1, a2a_2, …, ana_n, then x1x_1, x2x_2, …, xnx_n will be generated before y1y_1, y2y_2, …, yny_n.

For example, when n=3n = 3 and the generator is 132, the generation order of all permutations of {1,2,,n}\{1, 2, \dots, n\} is: 123, 132, 321, 312, 231, 213.

Given a permutation x1x_1, x2x_2, …, xnx_n, determine which generator makes this permutation appear as early as possible among all permutations, and which generator makes it appear as late as possible.

If multiple generators satisfy the requirement, output the lexicographically smallest one.

Input Format

The first line contains an integer nn. The second line contains a permutation x1x_1, x2x_2, …, xnx_n of {1,2,,n}\{1, 2, \dots, n\}.

Output Format

The first line outputs a permutation of {1,2,,n}\{1, 2, \dots, n\}, representing a generator that makes x1x_1, x2x_2, …, xnx_n appear as early as possible.

The second line outputs a permutation of {1,2,,n}\{1, 2, \dots, n\}, representing a generator that makes x1x_1, x2x_2, …, xnx_n appear as late as possible.

If multiple generators satisfy the requirement, output the lexicographically smallest one.

3
1 3 2
1 2 3
2 1 3

Hint

Constraints

  • For 30% of the testdata, n10n \le 10.
  • For 50% of the testdata, n200n \le 200.
  • For 90% of the testdata, n30000n \le 30000.
  • For 100% of the testdata, n500000n \le 500000.

Translated by ChatGPT 5