例2 :套圈
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.
题目意思就是求一堆坐标的最近两点距离的1/2.
解法分析:分治,首先按x坐标排序,取中点作为pivot, 递归求解pivot左侧的距离最小值 d1 和右侧距离最小值 d2, 取 d1 和 d2 的最小值d, 对x坐标为pivot - d 和 pivot + d内的点再进行处理,按y坐标排序,遍历这些点更新d,如果遍历的两点距离大于d 退出循环
代码:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
struct Point{
double x, y;
}point[100005];
int index[100005];
bool cmp1(Point x, Point y){
return x.x < y.x;
}
bool cmp2(int x, int y)
{
return point[x].y < point[y].y;
}
double d(Point x, Point y)
{
return sqrt((x.x - y.x)*(x.x - y.x) + (y.y - x.y)*(y.y - x.y));
}
double search(int head, int tail){
if(tail - head == 1)
{
return d(point[head], point[tail]);
}
if(tail - head == 2)
{
return min(d(point[head], point[head+1]), d(point[head+1], point[tail]));
}
int pivot;
pivot = (head + tail)>>1;
double res, minl, minr;
minl = search(head, pivot);
minr = search(pivot + 1, tail);
res = min (minl, minr);
int i, j;
int num = 0;
for (i = head; i <= tail; i++)
{
if(point[i].x <= point[pivot].x + res && point[i].x >= point[pivot].x - res)
{
index[num] = i;
num++;
}
}
sort(index, index + num, cmp2);
for (i = 0; i < num;i++)
{
for(j = i + 1; j < num; j++ )
{
if(point[index[j]].y - point[index[i]].y >= res )
{
break;
}
res = min(res, d(point[index[j]], point[index[i]]));
}
}
return res;
}
int main(int argc, char** argv) {
int n;
int i;
while(1)
{
scanf("%d", &n);
if (!n)
{
break;
}
for(i = 0; i < n; i++)
{
scanf("%lf %lf", &point[i].x, &point[i].y);
}
sort(point, point + n, cmp1);
printf("%.2lf\n", search(0, n-1)/2);
}
return 0;
}
总结:因为老师说可以用快排所以这里使用了,其实不是必要的。