Longest Increasing Subsequence 4

Find a longest strictly increasing subsequence of A, and among all of maximum length output the lexicographically smallest one along with its length.

Medium7Dynamic programmingBinary searchGreedyArrayInterviewNo attempts yetTime limit1sMemory limit256 MB

Problem

A sequence AA is given. Pick some elements of AA, keep their original order, and join them: the result is a subsequence of AA. If the values of that subsequence always grow from left to right, it is an increasing subsequence.

Write a program that finds a longest increasing subsequence of AA and prints its length together with its elements.

For example, if A={10,20,10,30,20,50}A = \{10, 20, 10, 30, 20, 50\}, a longest increasing subsequence takes the first, second, fourth, and sixth elements, giving {10,20,30,50}\{10, 20, 30, 50\} with length 44.

There can be several increasing subsequences of maximum length. In that case only the lexicographically smallest one counts as the answer. Between two sequences of the same length, compare values from the front: the one with the smaller value at the first position where they differ is lexicographically smaller.

Input

The first line contains the length NN of the sequence AA. (1N1,0001 \le N \le 1{,}000)

The second line contains the elements A1,A2,,ANA_1, A_2, \dots, A_N separated by spaces. (1Ai1,0001 \le A_i \le 1{,}000)

Output

Print the length of a longest increasing subsequence of AA on the first line.

Print the elements of that subsequence on the second line, in order, separated by single spaces. If several increasing subsequences have the maximum length, print the lexicographically smallest one.