#P7686. Simplifying Stable Sort Sequences
Simplifying Stable Sort Sequences
Simplifying Stable Sort Sequences
You are given a sequence of sort operations applied to a table with columns numbered from \(1\) to \(C\). Each operation Sort(k) sorts the rows of the table in increasing order based on the values in column \(k\) and the sort is stable (i.e. if two rows have equal values in column \(k\), their relative order remains unchanged).
A sequence of sort operations is provided. Two sequences are said to be equivalent if, for any table, they yield the same final sorted order. For instance, executing the sequence:
Sort(2); Sort(2); Sort(1)
is equivalent to executing:
Sort(2); Sort(1)
because the repeated Sort(2) is redundant. The task is to remove all redundant operations from the given sequence such that the resulting (simplified) sequence is equivalent to the original one. Hint: Due to the stability of the sort operations, if a column is sorted more than once, only the position of its last occurrence in the sequence matters. A typical approach is to traverse the sequence from right to left and, whenever you encounter a sort operation on a column you haven't seen yet, keep it; after processing, reverse the collected operations to get the effective sequence in the original left-to-right order.
inputFormat
The first line of input contains two integers \(N\) and \(C\) where \(N\) represents the number of sort operations and \(C\) represents the number of columns in the table (columns are numbered from \(1\) to \(C\)).
The second line contains \(N\) integers \(k_1, k_2, \ldots, k_N\), with each \(k_i\) (\(1 \le k_i \le C\)) indicating that a Sort(\(k_i\)) operation is applied.
outputFormat
Output a single line starting with an integer \(M\), the number of operations in the simplified sequence, followed by \(M\) integers representing the effective (simplified) sort operations in the order they should be applied (from left to right).
Example: For input
7 5 2 3 2 1 3 2 1
the correct output is
3 3 2 1
Explanation: Scanning the sequence from right to left you collect the unique operations in order: [1, 2, 3]. Reversing them gives [3, 2, 1] with count 3.
sample
3 3
1 1 2
2 1 2