problems / 274

Dance Partners on the Pier (medium version)

medium linked-list heap simulation 1000 ms · 256 MB

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.

Example 1

Input

8
10 3 7 8 1 20 14 12

Output

3 4
2 5
7 8
1 6

Example 2

Input

7
1 5 5 2 2 9 1

Output

2 3
4 5
1 6

Hints · reveal one at a time if you're stuck

Hint 1

When two neighbours leave, how many neighbour pairs of the line actually change? Which pairs disappear, and which single new pair appears?

Hint 2

Keep the line as a doubly linked list so a pair can be removed in O(1), and keep the candidate pairs in a structure that returns the smallest (difference, left number) quickly. Removing pairs that went stale from it is awkward: can you just recognize and skip them when they come out?

Hint 3

Use a min-heap of pairs over a doubly linked list, with lazy deletion: a popped pair is valid only if both of its dancers are still in line.

report an issue Prefer your own editor? sooks prep 274 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.