您的位置:首页 > 大数据 > 人工智能

[分治]UVA10245 The Closest Pair Problem

2014-04-04 11:09 381 查看
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升序进行排列,然后定义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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  分治