Dance Partners on the Pier (medium version)
The only difference from the easy version (problem 273) is the constraint on n: here the pier holds up to 2·10^5 dancers.
n dancers stand in a line along the pier, numbered 1 to n from left to right. Dancer i has skill level a_i.
While at least two dancers are still in the line, the following happens:
- Among all pairs of dancers who currently stand next to each other, pick the pair whose skill levels differ the least, that is, with the smallest
|a_x − a_y|. If several pairs share the smallest difference, pick the leftmost one. - Those two dancers leave the line to dance together, and the dancers on either side of the gap step closer, so they become neighbours.
If n is odd, one dancer is left standing at the end.
Print the pairs in the order they leave the line.
Input
The first line contains an integer n (2 ≤ n ≤ 2·10^5), the number of dancers.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9), the skill levels from left to right.
Output
Print ⌊n/2⌋ lines. The k-th line describes the k-th pair to leave: the original numbers of its two dancers, the left one first, separated by a space.
Notes
In the first example, the neighbouring differences are 7 4 1 7 19 6 2, so dancers 3 and 4 leave first. Dancers 2 and 5 (skills 3 and 1) become neighbours with a difference of 2, which ties with dancers 7 and 8; the leftmost pair, 2 and 5, goes next. Now dancers 1 and 6 are neighbours with a difference of 10, so dancers 7 and 8 leave before them.
In the second example, two pairs have difference 0, and the leftmost one, dancers 2 and 3, leaves first. Then dancers 4 and 5 leave. The line is now dancers 1, 6 and 7, both neighbouring differences are 8, so dancers 1 and 6 leave and dancer 7 is left standing.