Connectivity of a Permutation Graph
Time limit2sMemory limit256 MB
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.
Problem
A permutation of size is a sequence of length in which every integer from to appears exactly once. Denote such a permutation by .
From a permutation we build a permutation graph: an undirected graph on vertices numbered , in which two vertices and () are joined by an edge whenever .
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 can be as large as , the graph may contain up to 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 ().
The second line contains space-separated integers, the elements of the permutation.
Output
On the first line, print the number of connected components .
On each of the next lines, print one component: first its size , then the 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.
