CF BUDDY
← Problems·

1237C2 · Balanced Removals (Harder)

1900 · binary search, constructive algorithms, divide and conquer

Problem: This is a harder version of the problem. In this version, n50000n \le 50\,000.

There are nn distinct points in three-dimensional space numbered from 11 to nn. The ii-th point has coordinates (xi,yi,zi)(x_i, y_i, z_i). The number of points nn is even.

You'd like to remove all nn points using a sequence of n2\frac{n}{2} snaps. In one snap, you can remove any two points aa and bb that have not been removed yet and form a perfectly balanced pair. A pair of points aa and bb is perfectly balanced if no other point cc (that has not been removed yet) lies within the axis-aligned minimum bounding box of points aa and bb.

Formally, point cc lies within the axis-aligned minimum bounding box of points aa and bb if and only if min(xa,xb)xcmax(xa,xb)\min(x_a, x_b) \le x_c \le \max(x_a, x_b), min(ya,yb)ycmax(ya,yb)\min(y_a, y_b) \le y_c \le \max(y_a, y_b), and min(za,zb)zcmax(za,zb)\min(z_a, z_b) \le z_c \le \max(z_a, z_b). Note that the bounding box might be degenerate.

Find a way to remove all points in n2\frac{n}{2} snaps.

Input Format: The first line contains a single integer nn (2n500002 \le n \le 50\,000; nn is even), denoting the number of points.

Each of the next nn lines contains three integers xix_i, yiy_i, ziz_i (108xi,yi,zi108-10^8 \le x_i, y_i, z_i \le 10^8), denoting the coordinates of the ii-th point.

No two points coincide.

Output Format: Output n2\frac{n}{2} pairs of integers ai,bia_i, b_i (1ai,bin1 \le a_i, b_i \le n), denoting the indices of points removed on snap ii. Every integer between 11 and nn, inclusive, must appear in your output exactly once.

We can show that it is always possible to remove all points. If there are many solutions, output any of them.

Note: In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z=0z = 0 plane). Note that order of removing matters: for example, points 55 and 11 don't form a perfectly balanced pair initially, but they do after point 33 is removed.

Sample Cases

Case 1

Input

6
3 1 0
0 3 0
2 2 0
1 0 0
1 3 0
0 1 0

Output

3 6
5 1
2 4

Case 2

Input

8
0 1 1
1 0 1
1 1 0
1 1 1
2 2 2
3 2 2
2 3 2
2 2 3

Output

4 5
1 6
2 7
3 8

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback