hdu1007分治法

來源:互聯網
上載者:User


  • 把所有點按x座標的大小排序,從中間一份為二。
  • 最近點對有三種情況,都在左邊,都在右邊,左右都有
  • 遞迴求出都在左邊和都在右邊的情況,選一個最小值curmin。
  • 然後求出兩邊各有一個的情況得結果為tmp,求法請參考給個連結
  • 取tmp和curmin的最小值為結果

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;

typedef struct node
{
double x;
double y;
}point;
point p[100001];
point y[100001];

int cmp_x(point a, point b)
{
return a.x < b.x;
}

int cmp_y(point a, point b)
{
return a.y < b.y;
}

double dist(point a, point b)
{
return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
}

double find_near(int l, int r)
{
if (r - l == 1)
return dist(p[l], p[r]);
if (r - l == 2)
return min(min(dist(p[l], p[l+1]), dist(p[l+1], p[l+2])), dist(p[l], p[l+2]));

int mid = (l+r) / 2;
double curmin = min(find_near(l, mid), find_near(mid+1, r));
int ith = 0;
int i,j;
for (i = l; i <= r; i++)
{
if (p[mid].x - p[i].x <= curmin || p[i].x - p[mid].x <= curmin)
y[ith++] = p[i];
}
sort(y, y + ith, cmp_y);
int num;
for (i = 0; i < ith; ++i)
for (j = i+1, num = 0; j < ith && num < 7; ++num, ++j)
if ( dist(y[i], y[j]) < curmin )
curmin = dist(y[i], y[j]);
else
break;
return curmin;

}
int main()
{
//freopen("in.txt", "r", stdin);
int n;
while (cin >> n && n)
{
int i;
for (i = 0; i < n; ++i)
scanf("%lf%lf", &p[i].x, &p[i].y);
sort(p, p+n, cmp_x);
printf("%.2lf\n", find_near(0, n-1)/2);
}
return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.