欢迎关注更多精彩
关注我,学习常用算法与数据结构,一题多解,降维打击。
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1007
根据这里的分析
https://blog.csdn.net/junerfsoft/article/details/2975495
合并时只要将左边的点与右边最多6个点进行求距离。
#include <iostream>
#include <stdio.h>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 100000+10;
pair<double , double> points[N];
pair<double , double> leftP[N], rightP[N];
bool cmpY(pair<double , double> a, pair<double , double> b) {
return a.second<b.second;
}
double getDis(pair<double , double> a, pair<double , double> b) {
a.first-=b.first;
a.second -= b.second;
return sqrt(a.first*a.first+a.second*a.second);
}
double dm(int l, int r) {
if(l+1==r) return getDis(points[l], points[r]);
if(l+2==r) {
double ans = getDis(points[l], points[r]);
for(int i=l;i<r;i++) {
for (int j = i + 1; j <= r; ++j) {
ans = min(ans, getDis(points[i], points[j]));
}
}
return ans;
}
int mid = l+r>>1;
double leftMin = dm(l, mid);
double rightMin = dm(mid+1, r);
double minDis = min(leftMin, rightMin);
int leftLen=0, rightLen=0;
for(int i=l;i<=mid;i++) {
if(points[mid].first-points[i].first>minDis)continue;
leftP[leftLen++] = points[i];
}
for(int i=mid+1;i<=r;i++) {
if(points[i].first-points[mid+1].first>minDis)continue;
rightP[rightLen++] = points[i];
}
// 将Y轴排序
sort(leftP, leftP+leftLen, cmpY);
sort(rightP, rightP+rightLen, cmpY);
double t = minDis;
// 利用双指针找到i对应的第1个j,然后往对比6个。
for(int i=0, j=0;i<leftLen && j<rightLen;i++) {
for(;j<rightLen && leftP[i].second-rightP[j].second>t;j++);
for(int s=0;s<6 && j+s<rightLen;s++) {
minDis = min(minDis, getDis(leftP[i], rightP[j+s]));
}
}
return minDis;
}
void solve() {
int n=0;
while(scanf("%d", &n)!=EOF &&n) {
for(int i=0;i<n;i++) {
scanf("%lf%lf",&points[i].first, &points[i].second);
}
sort(points, points+n);
double m = dm(0, n-1)/2;
printf("%.2lf\n", m);
}
}
int main()
{
solve();
return 0;
}
本人码农,希望通过自己的分享,让大家更容易学懂计算机知识。