分治法求最近对问题

版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/84648066

首先感谢博主https://www.cnblogs.com/zuoyou151/p/9059903.html,让我收获很多,今天感觉很困,状态不佳,解析与讲解会改天补上,注明:我这里采用递归时是左闭右开区间,而博主采用的左闭右闭。

还有感谢“NX”童鞋为我调好VS2017,之前因为环境问题一直装不上,不过VS2017的调试是真的好用啊,哈哈!

Code

#include <algorithm>
#include <iostream>
#include <cmath>

#define INF 0x3f3f3f3f

using namespace std;

const int maxn = 1005;

typedef struct Point
{
	double x;
	double y;

} point;

int n;
point p[maxn];

double dist(point p1, point p2)
{
	return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}

bool cmp(point p1, point p2)
{
	return p1.x < p2.x;
}

bool cmp2(point p1, point p2)
{
	return p1.y < p2.y;
}

double solve(int left, int right)
{
	//cout << left << ", " << right << endl;
	if (right - left == 1)
	{
		return INF;
	}


	if (right - left == 2)
	{
		return dist(p[left], p[right - 1]);
	}

	int mid = (left + right) / 2;

	double d1 = solve(left, mid);
	double d2 = solve(mid, right);
	double d = min(d1, d2);

	int l = left;
	while (p[l].x < p[mid].x - mid && l < right) l++;

	int r = right - 1;
	while (p[r].x > p[mid].x + d && r >= left) r--;

	sort(p + l, p + r + 1, cmp2);

	double d3;
	for (int i = l; i <= r; i++)
	{
		for (int j = i + 1; j <= r; j++)
		{
			d = min(d, dist(p[i], p[j]));
		}
	}

	return d;
}

int main()
{
	cin >> n;
	for (int i = 0; i < n; i++) cin >> p[i].x >> p[i].y;

	sort(p, p + n, cmp);

	cout << solve(0, n) << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/easylovecsdn/article/details/84648066
今日推荐