Greedily Increasing Subsequence

Interview

Time limit1sMemory limit512 MB

Summary
Given a permutation, repeatedly take the leftmost unused element larger than the previous pick, and report the resulting subsequence.
Level

Medium4 of 10

Topics
Array, Simulation, Greedy, Implementation
Solved
No attempts yet

Problem

Given a permutation A=(a1,a2,…,aN)A = (a_1, a_2, \dots, a_N) of the integers 1,2,…,N1, 2, \dots, N, the greedily increasing subsequence (GIS) is defined as follows.

Let g1=a1g_1 = a_1. For every i>1i > 1, let gig_i be the leftmost integer in AA that is strictly larger than gi−1g_{i-1}. If no such integer exists for some ii, the GIS of the sequence is (g1,g2,…,gi−1)(g_1, g_2, \dots, g_{i-1}).

Given a permutation AA, compute the GIS of AA.

Input

The first line of input contains an integer 1≤N≤1061 \le N \le 10^6, the number of elements of the permutation AA. The next line contains NN distinct integers between 11 and NN, the elements a1,…,aNa_1, \dots, a_N of the permutation AA.

Output

First, output a line containing the length ll of the GIS of AA. Then output ll integers, the elements of the GIS in order.

Examples3

  1. Example 1

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

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

    Input
    5
    5 4 3 2 1
    
    Expected output
    1
    5