[分治]UVA10245 The Closest Pair Problem

Problem J
The Closest Pair Problem

Input: standard input
Output: standard output
Time Limit: 8 seconds
Memory Limit: 32 MB

 

Given a set of points in a two dimensional space, you will have to find the distance between the closest two points.

 

Input

 

The input file contains several sets of input. Each set of input starts with an integer N (0<=N<=10000), which denotes the number of points in this set. The next line contains the coordinates of N two-dimensional points. The first of the two numbers denotes the X-coordinate and the latter denotes the Y-coordinate. The input is terminated by a set whose N=0. This set should not be processed. The value of the coordinates will be less than 40000 and non-negative.

 

Output

 

For each set of input produce a single line of output containing a floating point number (with four digits after the decimal point) which denotes the distance between the closest two points. If there is no such two points in the input whose distance is less than 10000, print the line INFINITY.

 

Sample Input

3
0 0
10000 10000
20000 20000
5
0 2
6 67
43 71
39 107
189 140
0

 

Sample Output

INFINITY
36.2215

(World Final Warm-up Contest, Problem setter: Shahriar Manzoor)

 

 

“Generally, a brute force method has only two kinds of reply, a) Accepted b) Time Limit Exceeded.”


题意:给出N个点,找出这N个点中距离最近的点对。

思路:直接暴力的话,肯定超时,一开始想到使用分治,但是不确定,后来看了下网上人的解法,确实是使用分治,首先我们把坐标按x升序进行排列,然后定义LR分别为区间的左右端点(LR均代表点的标号),mid为区间中点,我们可以先分别暴力求出在[L,mid][mid,R]中最短的线段,不妨设其为min,当然最短线段还可能是两个点分别在两个区间之中,但如果存在这样的最短线段,那么线段的两个端点一定会在区间[a,b]中,并且x[mid]-x[a]>=minx[b]-x[mid]>=min,因为两点之间的距离大于等于两点横坐标差的绝对值。

代码:

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

using namespace std;

class Node
{
public:
    double x,y;
}node[10010];

bool cmp(Node s1,Node s2)
{
	return s1.x<s2.x;
}


double distance(Node s1,Node s2)
{
	return sqrt((s1.x-s2.x)*(s1.x-s2.x)+(s1.y-s2.y)*(s1.y-s2.y));
}

double dis(int left,int right)
{
	if(left==right) return 100000000.0;
	if(right-left==1) return distance(node[left],node[right]);
	int mid,i,j,k;
	double d,cnt;
	mid=(left+right)/2;
	d=min(dis(left,mid),dis(mid,right));
	for(i=mid-1;i>=left&&node[mid].x-node[i].x<d;i--)
		{
			for(j=mid+1;j<=right&&node[j].x-node[mid].x<d;j++)
				{
					cnt=distance(node[j],node[i]);
					if(cnt<d) d=cnt;
				}
		}
	return d;
}

int main()
{
    int num;
	while(cin>>num&&num)
		{
			int i;
			for(i=0;i<num;i++)
				{
					cin>>node[i].x>>node[i].y;
				}
			sort(node,node+num,cmp);
			double mindis=dis(0,num-1);
			if(mindis<10000.0)
				cout<<fixed<<setprecision(4)<<mindis<<endl;
			else
				cout<<"INFINITY"<<endl;
		}
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值