这一题一开始没有看懂,最后还是参考了网上大神的代码。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
/*
using namespace std;
#define INF 1e20
#define N 100010
struct Point
{
double x, y;
};
int n;
Point p[N];
int tmp[N];
double dis(int a, int b)
{
return sqrt((p[a].x - p[b].x)*(p[a].x - p[b].x) + (p[a].y - p[b].y)*(p[a].y - p[b].y));
}
bool cmp(Point a, Point b)
{
if (a.x != b.x)return a.x < b.x;
return a.y < b.y;
}
bool cmpy(int a, int b)
{
return p[a].y < p[b].y;
}
double solve(int l, int r)
{
if (l == r) return INF; //一个点的情况
if (l + 1 == r) return dis(l, r); //两个点的情况
int m = (l + r) >> 1;
double d1 = solve(l, m);
double d2 = solve(m + 1, r);
double d = min(d1, d2);
int k = 0;
for (int i = l; i <= r; i++) //分离出宽度为d的区间
{
if (fabs(p[m].x - p[i].x) <= d)
tmp[++k] = i;
}
sort(tmp + 1, tmp + k + 1, cmpy);
for (int i = 1; i <= k; i++) //线性扫描 ,判断是否有小于d的距离,由于是按y排序的,所以省去了不少步骤
{
for (int j = i + 1; j <= k && p[tmp[j]].y - p[tmp[i]].y < d; j++)
{
d = min(d, dis(tmp[i], tmp[j]));
}
}
return d;
}
int main()
{
while (scanf("%d", &n) && n)
{
for (int i = 1; i <= n; i++)
{
scanf("%lf%lf", &p[i].x, &p[i].y);
}
sort(p + 1, p + n + 1, cmp);
printf("%.2f\n", solve(1, n) / 2);
}
return 0;
}*/