传送站
题面:
This is a harder version of the problem. In this version, n≤50000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (xi,yi,zi). The number of points n is even.
You’d like to remove all n points using a sequence of n2 snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.
Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if min(xa,xb)≤xc≤max(xa,xb), min(ya,yb)≤yc≤max(ya,yb), and min(za,zb)≤zc≤max(za,zb). Note that the bounding box might be degenerate.
Find a way to remove all points in n2 snaps.
Input
The first line contains a single integer n (2≤n≤50000; n is even), denoting the number of points.
Each of the next n lines contains three integers xi, yi, zi (−108≤xi,yi,zi≤108), denoting the coordinates of the i-th point.
No two points coincide.
Output
Output n2 pairs of integers ai,bi (1≤ai,bi≤n), denoting the indices of points removed on snap i. Every integer between 1 and n, 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.
题意: 三维平面给你一堆点,让你两个两个的删,保证每次删除的两个点所围成的长方体中没有其他的点,求删点顺序。.
解析: 直接想三维平面的两个点删掉的策略可能不太好想,我们可以试着先从低维分析:
(1)如果是一维,如果事先把这些点排个序,直接按顺序把挨得近的两两删掉即可;
(2)如果是二维的话,如果我们事先将这些点以x为第一优先、y为第二优先的顺序排个序,我们也按照顺序将相邻的两个点两两删去也是可以的。
(3)所以在三维条件下,我们可以先事先把所有点从小到大排个序,先按x再按y再按z,然后先把一维的点都删掉,这里我们可以约定删xy相同的点,如果删完这些点还有剩余,我们就把x相同的点两两删掉,如果还有剩余就按顺序删掉这些点就行了。总结: 这里等同于说把三维分解为一维和二维进行操作,这也就是贪心的思想,有的问题看起来很复杂,如果能把这个问题分解,并能从局部最优推出全局最优,那么这些问题就很有可能要用到贪心,这道题便是典型的一个例子。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int maxn=5e4+7;
const int inf=0x3f3f3f3f;
const ll mod=1e9+7;
#define pb push_back
#define faster ios::sync_with_stdio(0),cin.tie(0)
int n;
struct node{
int x,y,z,id;
}no[maxn];
bool cmp(node a,node b){
if(a.x!=b.x)return a.x<b.x;
if(a.y!=b.y)return a.y<b.y;
return a.z<b.z;
}
vector<node> v;
vector<node> g;
void solve(){
for(int i=0;i<n;i++){//先删一维的点对
if(no[i].x==no[i+1].x){
if(no[i].y==no[i+1].y){
while(no[i].y==no[i+1].y){
printf("%d %d\n",no[i].id,no[i+1].id);
i+=2;
}
i--;
}
else v.pb(no[i]);
}
else v.pb(no[i]);
}
for(int i=0;i<(int)v.size();i++){//删二维点对
if(v[i].x==v[i+1].x){
printf("%d %d\n",v[i].id,v[i+1].id);
i++;
}
else g.pb(v[i]);
}
for(int i=0;i<(int)g.size();i+=2){//删二维点对
printf("%d %d\n",g[i].id,g[i+1].id);
}
}
int main()
{
faster;
cin>>n;
for(int i=0;i<n;i++){
cin>>no[i].x>>no[i].y>>no[i].z;
no[i].id=i+1;
}
sort(no,no+n,cmp);
no[n].x=no[n].y=no[n].z=inf;
solve();
return 0;
}