Time Limit: 30 Sec Memory Limit: 512 MB
Submit: 1162 Solved: 618
已知平面内 N 个点的坐标,求欧氏距离下的第 K 远点对。
输入文件第一行为用空格隔开的两个整数 N, K。接下来 N 行,每行两个整数 X,Y,表示一个点
的坐标。1 < = N < = 100000, 1 < = K < = 100, K < = N*(N−1)/2 , 0 < = X, Y < 2^31。
输出文件第一行为一个整数,表示第 K 远点对的距离的平方(一定是个整数)。
10 5 0 0 0 1 1 0 1 1 2 0 2 1 1 2 0 2 3 0 3 1
9
自己yy了一波,过了样例就A了hhh
考虑到$k$很小,因此我们可以维护一个$2*k$个点的小根堆去维护每个点对(每个点对会被统计两次)
然后在K-D tree上暴力,如果当前点对的距离比堆顶的距离大,就把堆顶删除,然后把当前点加入
时间复杂度$O(n \sqrt(n))?$
// luogu-judger-enable-o2
// luogu-judger-enable-o2
#include<cstdio>
#include<algorithm>
#include<queue>
#define int long long
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
using namespace std;
const int MAXN = 200001, INF = 1e9 + 10;
char buf[1 << 21], *p1 = buf, *p2 = buf;
inline int read() {
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int N, K;
priority_queue<int, vector<int>, greater<int> > q;
int root, WD, cur = 0;
#define ls(k) T[k].ls
#define rs(l) T[k].rs
struct Point {
int x[2];
bool operator < (const Point &rhs) const {
return x[WD] < rhs.x[WD];
}
}p[MAXN];
struct KDtree {
int ls, rs, mi[2], mx[2];
Point tp;
}T[MAXN];
inline int sqr(int x) {
return x * x;
}
void update(int k) {
for(int i = 0; i <= 1; i++) {
T[k].mi[i] = T[k].mx[i] = T[k].tp.x[i];
if(ls(k)) T[k].mi[i] = min(T[k].mi[i], T[ls(k)].mi[i]), T[k].mx[i] = max(T[k].mx[i], T[ls(k)].mx[i]);
if(rs(k)) T[k].mi[i] = min(T[k].mi[i], T[rs(k)].mi[i]), T[k].mx[i] = max(T[k].mx[i], T[rs(k)].mx[i]);
}
}
int Build(int l, int r, int wd) {
if(l > r) return 0;
WD = wd;
int k = ++cur, mid = l + r >> 1;
nth_element(p + l, p + mid, p + r + 1);
T[k].tp = p[mid];
T[k].ls = Build(l, mid - 1, wd ^ 1);
T[k].rs = Build(mid + 1, r, wd ^ 1);
update(k);
return k;
}
int dis(Point a, Point b) {
return sqr(a.x[0] - b.x[0]) + sqr(a.x[1] - b.x[1]);
}
int GetMaxDis(KDtree a, Point b) {
int rt = 0;
for(int i = 0; i <= 1; i++)
rt += sqr(max(abs(b.x[i] - a.mi[i]), abs(b.x[i] - a.mx[i])));
return rt;
}
void Query(int k, Point a) {
int tmp = q.top(), tmpdis = dis(T[k].tp, a);
if(tmpdis > tmp) q.pop(), q.push(tmpdis);
int disl = -INF, disr = -INF;
if(ls(k)) disl = GetMaxDis(T[ls(k)], a);
if(rs(k)) disr = GetMaxDis(T[rs(k)], a);
if(disl > disr) {
if(disl > q.top()) Query(ls(k), a);
if(disr > q.top()) Query(rs(k), a);
}
else {
if(disr > q.top()) Query(rs(k), a);
if(disl > q.top()) Query(ls(k), a);
}
}
main() {
#ifdef WIN32
freopen("a.in", "r", stdin);
#endif
N =read(); K = read();
for(int i = 1; i <= N; i++)
p[i].x[0] = read(), p[i].x[1] = read();
root = Build(1, N, 0);
for(int i = 1; i <= 2 * K; i++)
q.push(0);
for(int i = 1; i <= N; i++)
Query(root, p[i]);
printf("%lld", q.top());
}