#P7686. [CEOI 2005] Multi-key Sorting

[CEOI 2005] Multi-key Sorting

Description

Consider a table with rows and columns. The columns are numbered from 11 to CC. For simplicity, the entries in the table are strings consisting of lowercase letters.
TuLi
You are given Sort(kk) operations on such tables: Sort(kk) sorts the rows of the table by the values in column kk (the order of columns does not change). The sorting is stable, meaning that rows with equal values in column kk keep their original relative order. For example, applying Sort(22) to table 11 produces table 22.
We are interested in sequences of such sorting operations. These operations are applied one after another to the same table. For example, applying the sequence Sort(22); Sort(11) to table 11 produces table 33.
Two sequences of sorting operations are called equivalent if they have the same effect on any table. For example, Sort(22); Sort(22); Sort(11) is equivalent to Sort(22); Sort(11). However, it is not equivalent to Sort(11); Sort(22), because the effect on table 11 is different.

Input Format

The first line contains two integers, CC and NN. CC is the number of columns, and NN is the number of sorting operations. The second line contains NN integers, kik_i. It defines the sequence of sorting operations Sort(k1k_1); \cdots; Sort(kNk_N).

Output Format

The first line contains an integer MM, the length of the shortest sorting-operation sequence that is equivalent to the given sequence. The second line contains MM integers, describing this shortest sequence.

4 6
1 2 1 2 3 3
3
1 2 3

Hint

Constraints

For 100%100\% of the data, 1C1061 \leq C \leq 10^6, 1N3×1061 \leq N \leq 3×10^6, 1kiC1 \leq k_i \leq C.

Problem Notes

From Multi-key Sorting, CENTRAL-EUROPEAN OLYMPIAD IN INFORMATICS 2005.
Translated and organized by @求学的企鹅.

Translated by ChatGPT 5