#P2475. [SCOI2008] 斜堆

[SCOI2008] 斜堆

Description

A skew heap is a commonly used data structure. It is also a binary tree and satisfies the same heap property as a binary heap: every non-root node has a value larger than its parent. Therefore, in the whole skew heap, the root has the minimum value.

A skew heap does not need to be balanced, and there is no restriction on the relative sizes of the left and right children of any node. In this problem, all values in the skew heap are distinct.

To insert a new element XX into a skew heap HH, proceed recursively: when HH is empty or XX is smaller than the root of HH, XX becomes the new root, and the original root (if any) becomes the left child of XX.

When XX is greater than the root of HH, swap the two subtrees of the root, and (recursively) insert XX into the left subtree after the swap.

You are given a skew heap that contains each of the values 0,1,,n0, 1, \dots, n exactly once. Find a sequence of nodes such that this skew heap can be obtained by inserting these nodes one by one into an empty tree. If multiple answers exist, output the lexicographically smallest one.

The input is guaranteed to have a solution.

Input Format

The first line contains an integer nn. The second line contains nn integers d1,d2,,dnd_1, d_2, \dots, d_n. di<100d_i < 100 means ii is the left child of did_i, and di100d_i \ge 100 means ii is the right child of di100d_i - 100. Obviously 00 is always the root, so d0d_0 does not appear in the input.

Output Format

Output a single line containing n+1n+1 integers, i.e., the lexicographically smallest insertion sequence.

6
100 0 101 102 1 2
0 1 2 3 4 5 6
6
100 0 2 102 4 104
4 6 5 2 0 1 3
7
0 100 1 102 2 3 5
2 5 0 3 4 6 7 1

Hint

Constraints: 2n502 \le n \le 50.

Translated by ChatGPT 5