蛮力法和分治法求最近对

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ancientear/article/details/83826467
//蛮力法
#include<iostream>
#include<math.h>
#include<time.h>
#include<stdlib.h>
using namespace std;
struct P
{
    int x;
    int y;
};
double ClosePoints(int n,P a[],int &index1,int &index2)
{
    double  d;
    double  Dist=10000;
    for (int i=0;i<n-1;i++)
    {
        for (int j=i+1;j<=n-1;j++)
        {
            d=(a[i].x-a[j].x)*(a[i].x-a[j].x)+(a[i].y-a[j].y)*(a[i].y-a[j].y);
            if(d<=Dist)
            {
                Dist=d;
                index1=i;
                index2=j;
            }
        }
    }  return Dist;
}
int main (void)
{
    clock_t start,end;
    int g;
    int s,e;
    P a[10000];
    for (int i=1;i<4;i++)
    {
        cout<<"输入坐标的个数";
        cin>>g;
        srand(time(NULL));
        for (int r=0;r<g;r++)
        {
            a[r].x=rand()%(g-123);
            a[r].y=rand()%(g-1234);
        }
        start=clock();
        double w=ClosePoints(g,a,s,e);
        end=clock();
        cout<<"最近的两个点是:P1("<<a[s].x<<","<<a[s].y<<") P2("<<a[e].x<<","<<a[e].y<<")"<<endl;   cout<<"距离是:"<<sqrt(w)<<endl;
        cout<<"蛮力法求最近对用时:"<<(double)(end-start)/CLOCKS_PER_SEC<<"ms"<<endl;
  
    }
    
}

    // 分治算法求最近点对
#include<iostream>
#include<algorithm>
#include<cmath>
#define MAX 100000
using namespace std;

struct point {
    double x, y;
}p[100005];

int a[100005];// 保存排序的索引

int cmpx(const point& a, const point& b) {
    return a.x < b.x;
}

int cmpy(int &a, int &b) {
    return p[a].y < p[b].y;
}

inline double min(double a, double b) {
    return a < b ? a : b;
}
inline double dist(const point& a, const point& b) {
    return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
}
double closeset(int low, int high) {
    if (low == high)
        return MAX;
    if (low + 1 == high)
        return dist(p[low], p[high]);
    
    int mid = (low + high)>>1;
    
    double ans = min(closeset(low, mid), closeset(mid+1, high));
    
    int i, j, cnt = 0;
    for (i = low; i <= high; i++) {
        if (p[mid].x - ans <= p[i].x && p[i].x <= p[mid].x + ans)
            a[cnt++] = i;
    }
    sort(a, a + cnt, cmpy);
    
    for (i = 0; i < cnt; i++) {
        int k = i+7 > cnt ? cnt : i+7;
        for (j = i+1; j < k; j++) {
            if (p[a[j]].y - p[a[i]].y > ans)
                break;
            ans = min(dist(p[a[i]], p[a[j]]), ans);
        }
    }
    return ans;
}
int main() {
    int n;
    while(cin >> n && n != 0) {
        for (int i = 0; i < n; i++)
            cin >> p[i].x >> p[i].y;
        sort(p, p + n, cmpx);
        printf("分治法求解%.2f\n", closeset(0, n-1)/2);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ancientear/article/details/83826467