1-D closet pair 二分法

来源:互联网 发布:桔子浏览器 知乎 编辑:程序博客网 时间:2024/06/11 14:43
/**************************  解题思路:二分法  。。。。。。。。。。。。。。。。。。。。。。。。。  left                    mid                 right    点到自身的距离设为inf   递归边界:返回两个点的距离     两个点最近:  分布的情况:(1)两个点都在left-mid            (2)两个点都在right-mid(3)两个点在mid两边:即 mid 与 mid+1的距离最短距离即为三种情况中最短的一条    *******************************/#include<iostream>#include<algorithm>#include<cmath>#include<cstdio>#include<iomanip>using namespace std;const int inf = 0xffffff;double closest(int start, int end, double A[] ){    double th,thL,thR,p,q,minn,maxn;    if(end-start==1)        th = abs(A[start]-A[end]);    else if(start==end)        th=inf;    else{        int mid = (start+end)/2;        thL = closest(start,mid,A);        thR = closest(mid+1,end,A);        maxn = A[mid];        minn = A[mid+1];        th = min(thL,thR);        th = min(th,minn-maxn);    }    return th;}int main(){    int n;    while(cin >>n)    {        double A[n+10];        for(int i=0;i<n;i++)            cin >> A[i];        sort(A,A+n);        double cl = closest(0,n-1,A);        cout << fixed << setprecision(6) << cl << endl;    }    return 0;;}                                 

                   
0 0
原创粉丝点击