POJ 2966 k-d Tree

POJ 2966 k-d Tree_第1张图片

 

题意:二维平面中有n个点,求每个点和其他点的最远距离

 

#include
#include
#include
#include
using namespace std;
#define ll long long
const int maxm = 100005;
const ll INF = 1e18;
struct node
{
	ll d[2];
}p[maxm], q[maxm];
int nD;
bool operator<(node a, node b)
{
	return a.d[nD] < b.d[nD];
}
ll Sqr(ll x)
{
	return x*x;
}
ll Dis(node a, node b)
{
	ll ans = 0;
	for (int i = 0;i < 2;i++)
		ans += (a.d[i] - b.d[i])*(a.d[i] - b.d[i]);
	if (ans == 0) ans = INF;
	return ans;
}
void Build(int l, int r, int D)
{
	if (l >= r)return;
	int mid = (l + r) / 2;nD = D;
	nth_element(p + l, p + mid, p + 1 + r);
	Build(l, mid - 1, D ^ 1);
	Build(mid + 1, r, D ^ 1);
}
ll Query(node now, int l, int r, int D)
{
	int mid = (l + r) / 2;
	if (l == r)
		return Dis(now, p[l]);
	if (l > r) return INF;
	ll dn, dc;
	dn = Dis(now, p[mid]);
	if (now.d[D] < p[mid].d[D])
	{
		dc = Query(now, l, mid - 1, D ^ 1);
		if (dc > Sqr(now.d[D] - p[mid].d[D]))
			dc = min(dc, Query(now, mid + 1, r, D ^ 1));
	}
	else
	{
		dc = Query(now, mid + 1, r, D ^ 1);
		if (dc > Sqr(now.d[D] - p[mid].d[D]))
			dc = min(dc, Query(now, l, mid - 1, D ^ 1));
	}
	return min(dn, dc);
}
int main()
{
	int i, j, t, n;ll ans;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d", &n);
		for (i = 1;i <= n;i++)
		{
			scanf("%lld%lld", &p[i].d[0], &p[i].d[1]);
			q[i] = p[i];
		}
		Build(1, n, 0);
		for (i = 1;i <= n;i++)
		{
			ans = Query(q[i], 1, n, 0);
			printf("%lld\n", ans);
		}
	}
	return 0;
}

 

你可能感兴趣的:(其他)