题目传送门
Problem Description
Have you ever played quoit in a playground? Quoit is a game in which flat rings are pitched at some toys, with all the toys encircled awarded.
In the field of Cyberground, the position of each toy is fixed, and the ring is carefully designed so it can only encircle one toy at a time. On the other hand, to make the game look more attractive, the ring is designed to have the largest radius. Given a configuration of the field, you are supposed to find the radius of such a ring.
Assume that all the toys are points on a plane. A point is encircled by the ring if the distance between the point and the center of the ring is strictly less than the radius of the ring. If two toys are placed at the same point, the radius of the ring is considered to be 0.
Input
The input consists of several test cases. For each case, the first line contains an integer N (2 <= N <= 100,000), the total number of toys in the field. Then N lines follow, each contains a pair of (x, y) which are the coordinates of a toy. The input is terminated by N = 0.
Output
For each test case, print in one line the radius of the ring required by the Cyberground manager, accurate up to 2 decimal places.
Sample Input
2
0 0
1 1
2
1 1
1 1
3
-1.5 0
0 0
0 1.5
0
Sample Output
0.71
0.00
0.75
给定n个点求两点之间的最近距离 / 2,强行暴力算法复杂度是O(n^2)。这个基本上都会写就不说了但是会TLE。正确的解法是最近点对的分治解法,时间复杂度是O(NlogN)。
分治思想很好的应用,总体时间复杂度O(NlogN)
#include
#include
#include
#include
#include
using namespace std;
const double inf = 1e20;
struct point{
double x,y;
}p[100005],t[100005];
bool cmpxy(point a,point b) //按照x从小到大,x相等y从小到大排序
{
if(a.x != b.x){
return a.x < b.x;
}
else{
return a.y < b.y;
}
}
bool cmpy(point a,point b)
{
return a.y < b.y;
}
double dist(point a,point b)
{
double sum = (a.x - b.x) * (a.x - b.x) + (a.y - b.y)*(a.y - b.y);
return 1.0*sqrt(sum);
}
double search(int left,int right)
{
if(left == right) return inf;
if(right - left == 1) return dist(p[left],p[right]);
int mid = (left + right)/2;
double d1 = search(left,mid); //左半区间最小值
double d2 = search(mid+1,right); //右半区间最小值
double d = min(d1,d2);
int k = 0;
for(int i = left;i <= right;i++){
if(fabs(p[i].x - p[mid].x) <= d){
t[k++] = p[i];
}
}
sort(t,t+k,cmpy);
for(int i = 0;i < k;i++){
for(int j = i+1;j < k;j++){
if(t[j].y - t[i].y >= d) break; //乐观剪枝,y的差值已经超过d就没有计算意义
d = min(d,dist(t[i],t[j]));
}
}
return d;
}
int main()
{
int n;
while(~scanf("%d",&n) && n){
for(int i = 0;i < n;i++){
scanf("%lf%lf",&p[i].x,&p[i].y);
}
sort(p,p+n,cmpxy);
double ans = search(0,n-1)/2;
printf("%.2f\n",ans);
}
return 0;
}
愿你走出半生,归来仍是少年~