跳到正文

题解

题解:P10459 Raid

Perfect_Youth约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月8日
篇幅
约 3 分钟
题目
P10459

版本

  1. v1当前

我们充分发扬人类智慧:

将所有点 xx 坐标从小到大排序,或者 yy 坐标排序。

根据数学直觉,在排序后,答案中的肯定不会离得太远。

所以我们只取每个点向后的 6565 个点来计算答案。

这样速度快得飞起,可以在 n=100000n=100000 时 27ms 内卡过。

代码如下:

C++
#include <bits/stdc++.h>
#define getchar()(p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1 , 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
char buf[1 << 21], *p1 = buf, *p2 = buf;

using namespace std;

inline
int read() {
	int x = 0, f = 1;
	char ch = getchar();
	while (ch < '0' || ch > '9') {
		if (ch == '-') f = -1;
		ch = getchar();
	}
	while (ch >= '0' && ch <= '9') {
		x = (x << 1) + (x << 3) + (ch ^ '0');
		ch = getchar();
	}
	return x * f;
}

const int N = 1e5 + 7;

int t, n;

long long ans;

struct node {
	int x, y;
}a[N], b[N];

inline
bool cmp1(node u, node v) {
	return u.x < v.x;
}

inline
bool cmp2(node u, node v) {
	return u.y < v.y;
}

inline
long long min(long long a, long long b) {
	return a > b ? b : a;
}

int main() {
	t = read();
	while (t--) {
		n = read();
		ans = 2e18;
		for (int i = 1; i <= n; i++) a[i].x = read(), a[i].y = read();
		for (int i = 1; i <= n; i++) b[i].x = read(), b[i].y = read();
		sort(a + 1, a + 1 + n, cmp1);
		sort(b + 1, b + 1 + n, cmp1);
		for (int i = 1; i <= n; i++) {
			for (int j = i + 1; j <= min(n, i + 65); j++) {
				ans = min(ans, 1ll * (a[i].x - b[j].x) * (a[i].x - b[j].x) + 1ll * (a[i].y - b[j].y) * (a[i].y - b[j].y));
			}
		}
		sort(a + 1, a + 1 + n, cmp2);
		sort(b + 1, b + 1 + n, cmp2);
		for (int i = 1; i <= n; i++) {
			for (int j = i + 1; j <= min(n, i + 65); j++) {
				ans = min(ans, 1ll * (a[i].x - b[j].x) * (a[i].x - b[j].x) + 1ll * (a[i].y - b[j].y) * (a[i].y - b[j].y));
			}
		}
		printf ("%.3Lf\n", sqrtl(ans));
	}
	return 0;
}
原文