Given a set of points in a two dimensional space, you will have to find the distance between the closest two points.
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 N 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.
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.
(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升序进行排列,然后定义L、R分别为区间的左右端点(L、R均代表点的标号),mid为区间中点,我们可以先分别暴力求出在[L,mid]、[mid,R]中最短的线段,不妨设其为min,当然最短线段还可能是两个点分别在两个区间之中,但如果存在这样的最短线段,那么线段的两个端点一定会在区间[a,b]中,并且x[mid]-x[a]>=min,x[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; }