当前位置 : 主页 > 手机开发 > ios >

最近点对 (迭代器访问数据)

来源:互联网 收集:自由互联 发布时间:2021-06-11
#includeiostream#includestdio.h#includevector#includealgorithm#includetime.h#includeset#pragma warning(disable:4996)using namespace std;struct coordinate {int x, y;};bool cmp_x(coordinate a, coordinate b) {return a.x b.x;}bool cmp_y(coordin
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<time.h>
#include<set>
#pragma warning(disable:4996)
using namespace std;
struct coordinate {
	int x, y;
};
bool cmp_x(coordinate &a, coordinate &b) {
	return a.x < b.x;
}
bool cmp_y(coordinate &a, coordinate &b) {
	return a.y < b.y;
}
int n;
double distance(double x1, double x2, double y1, double y2)
{
	return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}
double min(double a, double b)
{
	return a < b ? a : b;
}
double merge(int l, int r, vector<coordinate> &v)
{
	if (r == l) return 0xffffff;
	if (r - l == 1) return distance(v[l].x, v[r].x, v[l].y, v[r].y);
	int mid = (l + r) >> 1;
	double d1 = merge(l, mid, v);
	double d2 = merge(mid, r, v);
	double d = min(d1, d2);
	vector<coordinate>p1, p2;
	int i = mid, j = mid;
	while (i >= l && v[i].x >= v[mid].x - d) p1.push_back(v[i]), i--;
	while (j <= r && v[j].x <= v[mid].x + d)p2.push_back(v[j]), j++;
	sort(p1.begin(), p1.end(), cmp_y);
	sort(p2.begin(), p2.end(), cmp_y);
	double min1 = 0xffffff, min2 = 0xffffff;
	for (vector<coordinate>::iterator it = p1.begin(); it < p1.end(); it++) {
		for (int j = 1; j < 8 && it + j < p1.end(); j++) {
			min1 = min(min1, distance((*it).x, (*(it + j)).x, (*it).y, (*(it + j)).y));//(*it).x
		}
	}
	for (vector<coordinate>::iterator it = p2.begin(); it < p2.end(); it++) {
		for (int j = 1; j < 8 && it + j < p2.end(); j++) {
			min2 = min(min2, distance((*it).x, (*(it + j)).x, (*it).y, (*(it + j)).y));
		}
	}
	return min(d, min(min1, min2));
}
int main()
{
	clock_t start, end;
	start = clock();
	srand(time(NULL));

	//cin >> n;
	n = rand() % 20 + 30;
	cout << n << endl;
	vector<coordinate>v(n + 1);
	//set<coordinate>ju;
	for (int i = 1; i <= n; i++) {
		v[i].x = rand() % 100, v[i].y = rand() % 100;
		//printf("%d %d\n", v[i].x, v[i].y);
	}
	sort(v.begin(), v.end(), cmp_x);
	double t = merge(1, n, v);
	int a, b, c, d;
	for (int i = 1; i <= n; i++) {
		printf("%d %d\n", v[i].x, v[i].y);
		if (i != 1) {
			if (distance(v[i].x, v[i - 1].x, v[i].y, v[i - 1].y) == t)
			{
				a = v[i].x, b = v[i].y, c = v[i - 1].x, d = v[i - 1].y;
				
			}
		}
	}

	printf("最近点对 :%d %d %d %d\n", a, b,c, d);
	end = clock();
	printf("\n时间 %f s\n", ((double)(end - start)) / CLOCKS_PER_SEC);
	printf("距离=%lf", t);
	getchar();
	getchar();
	return 0;
}
网友评论