This page is still under construction.

Parts of this page are still being built. What you see may change.

Connectivity of a Permutation Graph

Time limit2sMemory limit256 MB

Summary
Read a permutation of up to one million elements and report the connected components of the graph joining i and j whenever i < j and a_i > a_j.
Level

Medium7 of 10

Topics
Stack, Greedy, Graph, Array
Solved
No attempts yet

Problem

A permutation of size nn is a sequence of length nn in which every integer from 11 to nn appears exactly once. Denote such a permutation by a1,a2,…,ana_1, a_2, \dots, a_n.

From a permutation aa we build a permutation graph: an undirected graph on vertices numbered 1,2,…,n1, 2, \dots, n, in which two vertices ii and jj (1≤i<j≤n1 \le i < j \le n) are joined by an edge whenever ai>aja_i > a_j.

Find all connected components of this graph. Scanning the vertices from the smallest index to the largest, whenever you reach a vertex that has not been visited yet, gather it together with every vertex reachable from it into a single set (a connected component).

Because nn can be as large as 1 000 0001\,000\,000, the graph may contain up to O(n2)O(n^2) edges, so building every edge and running a naive depth-first search is too slow. Use the structure of the permutation to find the connected components efficiently.

Input

The first line contains the length of the permutation nn (1≤n≤1 000 0001 \le n \le 1\,000\,000).

The second line contains nn space-separated integers, the elements a1,a2,…,ana_1, a_2, \dots, a_n of the permutation.

Output

On the first line, print the number of connected components mm.

On each of the next mm lines, print one component: first its size sis_i, then the sis_i vertex numbers belonging to it in ascending order, separated by spaces.

When printing several components, sort them in ascending order by the smallest vertex number contained in each component.

Note

The picture below shows the permutation graph built from the permutation in the first example.

Examples3

  1. Example 1

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

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

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