#P1155. [NOIP 2008 提高组] 双栈排序
[NOIP 2008 提高组] 双栈排序
Description
Tom has been studying an interesting sorting problem. As shown in the figure, by using 2 stacks and , Tom hopes to sort the input sequence in ascending order using the following 4 operations.

- Operation : Push the first element of the input sequence onto stack .
- Operation : Pop the top element of to the output sequence.
- Operation : Push the first element of the input sequence onto stack .
- Operation : Pop the top element of to the output sequence.
If a permutation of can, via a series of valid operations, produce the output sequence , then Tom calls a "two-stack sortable permutation." For example, is a "two-stack sortable permutation," while is not. The following figure shows an operation sequence that sorts : .

Of course, there may be multiple such operation sequences. For the above example , is another valid operation sequence. Tom wants to know the lexicographically smallest operation sequence among them.
Input Format
The first line contains an integer .
The second line contains positive integers separated by spaces, forming a permutation of .
Output Format
Output a single line. If the input permutation is not a "two-stack sortable permutation," output 0.
Otherwise, output the lexicographically smallest operation sequence, with a space between every two operations and no trailing space at the end.
4
1 3 2 4
a b a a b b a b
4
2 3 4 1
0
3
2 3 1
a c a b b d
Hint
of the testdata satisfy: .
of the testdata satisfy: .
of the testdata satisfy: .
2021.06.17 strengthened by SSerxhs. Hack testdata are separated into a single subtask to avoid confusion.
NOIP 2008 Senior Problem 4.
Translated by ChatGPT 5
京公网安备 11011102002149号