Problem: This is a harder version of the problem. In this version, .
There are distinct points in three-dimensional space numbered from to . The -th point has coordinates . The number of points is even.
You'd like to remove all points using a sequence of snaps. In one snap, you can remove any two points and that have not been removed yet and form a perfectly balanced pair. A pair of points and is perfectly balanced if no other point (that has not been removed yet) lies within the axis-aligned minimum bounding box of points and .
Formally, point lies within the axis-aligned minimum bounding box of points and if and only if , , and . Note that the bounding box might be degenerate.
Find a way to remove all points in snaps.
Input Format: The first line contains a single integer (; is even), denoting the number of points.
Each of the next lines contains three integers , , (), denoting the coordinates of the -th point.
No two points coincide.
Output Format: Output pairs of integers (), denoting the indices of points removed on snap . Every integer between and , 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 plane). Note that order of removing matters: for example, points and don't form a perfectly balanced pair initially, but they do after point is removed.