Editorial
Let be the number of edges from vertex to a vertex with a larger index, and let be the number of edges from a vertex with a smaller index to vertex . Then .
Set and . When moving from to , the edges whose left endpoint is become newly included, while the edges whose right endpoint is are removed. Hence and we can uniquely recover from left to right by
For every , we must have and . If any condition fails, print .
Now process the vertices from to . For every previously processed vertex, maintain how many edges it still has to create toward vertices with larger indices. When processing vertex , exactly previous vertices must be connected to .
Choose the vertices with the largest remaining values. Store in a max-priority queue. Each time a pair with vertex is popped, add edge to the answer, decrease its remaining value by , and insert it again. After choosing vertices, insert . If there are too few vertices or the largest remaining value is , the construction is impossible. After processing all vertices, also verify that every remaining value is .
If the process succeeds, the recorded edges form a valid graph, so print the number of edges and the edge list.
Proof
Consider any feasible graph in which the current vertex is connected to a previous vertex but not to another previous vertex . Suppose their current remaining values satisfy .
Let be the number of printed edges. There are priority-queue operations, so the time complexity is . Storing the constructed edges uses space in the worst case.