#P1377. [TJOI2011] 树的序

[TJOI2011] 树的序

Description

It is well known that the shape of a binary search tree (BST) is closely related to the insertion order of keys. Specifically:

  1. Inserting a key kk into an empty tree yields a BST with a single node whose key is kk.
  2. When inserting a key kk into a non-empty tree, if kk is less than the key of its root, insert kk into its left subtree; otherwise, insert it into its right subtree.

We call an insertion sequence of keys for a BST a generating sequence of the tree. Given one generating sequence, find the lexicographically smallest generating sequence among all sequences that generate the same BST. Here, the lexicographic order means that for two generating sequences both of length nn, we first compare the first inserted keys, then the second, and so on.

Input Format

The first line contains an integer nn, the number of nodes in the BST. The second line contains nn positive integers k1,k2,,knk_1, k_2, \cdots, k_n, representing the generating sequence. For simplicity, k1knk_1 \sim k_n is a permutation of 11 to nn.

Output Format

One line with nn positive integers, which is the lexicographically smallest among all generating sequences that can generate the same BST.

4
1 3 4 2

1 3 2 4

Hint

Constraints and Conventions

  • For 20%20\% of the testdata, 1n101 \le n \le 10.
  • For 50%50\% of the testdata, 1n1001 \le n \le 100.
  • For 100%100\% of the testdata, 1n1051 \le n \le 10^5.

Translated by ChatGPT 5