Under construction

Still being built. Things may change

Multi-key Sorting

Time limit2sMemory limit128 MB

Summary
Given a sequence of stable column sorts, output the shortest equivalent sequence by keeping only the last occurrence of each column value in the order that determines the final effect.
Level

Medium4 of 10

Topics
Array, Greedy, Implementation
Solved
No attempts yet

Problem

Consider a table made of rows and columns. The columns are numbered from 1 to C. For simplicity, every cell of the table holds a string of lowercase letters.

Table 1

Col. 1Col. 2Col. 3
appleredsweet
applegreensour
peargreensweet
bananayellowsweet
bananabrownrotten

The operation Sort(k) reorders the rows of a table by the values in column k, leaving the order of the columns unchanged. The sort is stable: rows that have equal values in column k keep their original relative order. For example, applying Sort(2) to Table 1 yields Table 2.

Table 2 (Table 1 after Sort(2))

Col. 1Col. 2Col. 3
bananabrownrotten
applegreensour
peargreensweet
appleredsweet
bananayellowsweet

We are interested in sequences of such operations applied successively to the same table. For example, applying Sort(2); Sort(1) to Table 1 yields Table 3.

Table 3 (Table 1 after Sort(2); Sort(1))

Col. 1Col. 2Col. 3
applegreensour
appleredsweet
bananabrownrotten
bananayellowsweet
peargreensweet

Two sequences of operations are equivalent if they have the same effect on every table. For example, Sort(2); Sort(2); Sort(1) is equivalent to Sort(2); Sort(1), but it is not equivalent to Sort(1); Sort(2), because their effects on Table 1 differ.

Given a sequence of sort operations, determine a shortest equivalent sequence. This shortest equivalent sequence can be shown to be unique, so you must output exactly that sequence.

Input

The first line contains two integers C and N. C (1 ≤ C ≤ 1000000) is the number of columns and N (1 ≤ N ≤ 3000000) is the number of sort operations. The second line contains N integers k1 k2 … kN (1 ≤ ki ≤ C), describing the sequence Sort(k1); Sort(k2); …; Sort(kN).

Output

On the first line, print one integer M, the length of the shortest sequence of sort operations equivalent to the input sequence. On the second line, print exactly M integers, separated by single spaces, describing that sequence.

Examples6

  1. Example 1

    Input
    4 6
    1 2 1 2 3 3
    
    Expected output
    3
    1 2 3
    
  2. Example 2

    Input
    1 2
    1 1
    
    Expected output
    1
    1
    
  3. Example 3

    Input
    2 2
    1 2
    
    Expected output
    2
    1 2
    
  4. Example 4

    Input
    2 2
    2 1
    
    Expected output
    2
    2 1
    
  5. Example 5

    Input
    2 3
    2 2 1
    
    Expected output
    2
    2 1
    
  6. Example 6

    Input
    5 1
    5
    
    Expected output
    1
    5