10245 - The Closest Pair Problem

/*
推荐题型:三星,最近点对问题,典型分治法问题

题意:N为坐标个数,随后输入N个坐标,输出距离最近的两坐标的距离

分治策略:原来做这道题的时候观察n<10000,所以效率为N*N时也可以,想到了使用两个循环,然后剪枝,通过。
后来看别人代码,发现原来可以使用分治的,典型的分治问题,修改后的代码见方法二:
*/

#include <cstdio>
#include <cstdlib>
#include <cmath>
const int nMax=10007;
const double INF=40000*40000;
struct Node
{
	double x;
	double y;
}node[nMax];
int N;
double min;
int cmp(const void *a, const void *b)
{
	Node *pa = (Node *)a;
	Node *pb = (Node *)b;
	return pa->x > pb->x ? 1 : -1;
}
double cal(int i, int j)
{
	double a = node[i].x - node[j].x;
	double b = node[i].y - node[j].y;
	return sqrt(a * a + b * b);
}
void solve()
{
	int i, j;
	for(i = 0; i < N - 1; ++ i)
		for( j = i + 1;j < N; ++ j)
		{
			double res = cal(i, j);
			if(node[j].x - node[i].x >= min)
				break;
			if(res < min)
				min = res;
		}
}
int main()
{
	//freopen("f://data.in", "r", stdin);
	while(scanf("%d", &N) && N)
	{
		for(int i = 0; i < N; ++ i)
			scanf("%lf %lf", &node[i].x, &node[i].y);
		qsort(node, N, sizeof(node[0]), cmp);
		min=INF;
		solve();
		if(min < 10000)
			printf("%.4lf\n", min);
		else
			printf("INFINITY\n");
	}
	return 0;
}



//方法二:分治法实现。
#include <cstdio>
#include <cstdlib>
#include <cmath>
const int nMax = 10007;
const double INF = 40000 * 40000;
struct Node
{
	double x;
	double y;
}node[nMax];
int N;
double cal(int i, int j)
{
	double a = node[i].x - node[j].x;
	double b = node[i].y - node[j].y;
	return sqrt(a * a + b * b);
}
double bsearch(int a, int b)
{
	if(1 == b - a) return INF;
	int mid = a + (b - a) / 2;
	double min1 = bsearch(a, mid);
	double min2 = bsearch(mid, b);
	double min = min1 < min2 ? min1 : min2;
	int i, j;
	for(i = mid - 1; i >= a; -- i)
		for(j = mid; j < b; ++ j)
		{
			if(node[j].x - node[i].x >= min)
				break;
			if(cal(i, j) < min)
				min = cal(i, j);
		}
	return min;
}
int cmp(const void *a, const void *b)
{
	Node *pa = (Node *)a;
	Node *pb = (Node *)b;
	return pa->x > pb->x ? 1 : -1;
}
int main()
{
	//freopen("f://data.in", "r", stdin);
	while(scanf("%d", &N) && N)
	{
		for(int i = 0; i < N; ++ i)
			scanf("%lf %lf", &node[i].x, &node[i].y);
		qsort(node, N, sizeof(node[0]), cmp);
		double min=bsearch(0,N);
		if(min < 10000)
			printf("%.4lf\n", min);
		else
			printf("INFINITY\n");
	}
	return 0;
}

你可能感兴趣的:(struct,三星,pair)