最接近点对问题(分治)
Description
给定平面上n个点,找其中的一对点,使得在n个点组成的所有点对中,该点对间的距离最小。
Input
输入的第一行为测试样例的个数T,接下来有T个测试样例。每个测试的第一行是一个整数n( n < 10000 ),表示有n个点,接下来n行,每行两个整数X, Y表示点的坐标( |X| ≤ 1000,|Y| ≤ 1000 )。
Output
对应每个测试样例输出一行:最接近点对的距离,保留4位小数。
Sample Input
2
4
0 0
0 1
1 0
1 1
3
0 0
5 5
11 0
Sample Output
1.0000
7.0711
Author
Eapink
这道算法题其实很简单,但对于初涉及算法的同学来说还是有点难度,而且这道题是二维的最接近点对问题,建议第一次接触这道题的同学先弄明白一维情况下最接近点对问题,对于理解二维、三维情况下最接近点对问题会有一个好的基础。
一维情况下最接近点对问题
(大神可以忽略)
设直线l上有2m个点,以m为中点将l分割成两条线段dl,dr,然后求出dl和dr这两点条线段中的最小点距d1,d2,此时d=min{d1,d2},再通过计算出dl线段的中最大点与dr线段中的最小点之间的距离D,最小距离则为min{d,D}.
下面这部分是我从网上复制的一维最接近点对的源码- -
//2d10-1 一维最邻近点对问题
#include "stdafx.h"
#include <ctime>
#include <iostream>
using namespace std;
const int L=100;
//点对结构体
struct Pair
{
float d;//点对距离
float d1,d2;//点对坐标
};
float Random();
int input(float s[]);//构造S
float Max(float s[],int p,int q);
float Min(float s[],int p,int q);
template <class Type>
void Swap(Type &x,Type &y);
template <class Type>
int Partition(Type s[],Type x,int l,int r);
Pair Cpair(float s[],int l,int r);
int main()
{
srand((unsigned)time(NULL));
int m;
float s[L];
Pair d;
m=input(s);
d=Cpair(s,0,m-1);
cout<<endl<<"最近点对坐标为: (d1:"<<d.d1<<",d2:"