题意:
有N个士兵,N个炮台。给出这2N个点的坐标,求士兵距离炮台的最近距离。
思路:前面用分治法解决了这个问题,但是这个问题还能通过扫描线的方式进行乱搞,但是中间检查的范围是和分治法一样的。
首先按照x坐标进行排序,然后在map中我们实时维护和当前点的x坐标差不大于d的点的集合。
因为map中是按照y坐标有序的排列的,我们用lower_bound找到当前点的y坐标的下界y-d,然后检查y-d <= y <= y+d范围内的点就行了。
代码如下:
#include <cstdio>
#include <algorithm>
#include <set>
#include <cmath>
using namespace std;
const int MAX = 300010;
int T,N;
struct point{
double x,y;
int id;
point(){}
point(double xx, double yy, int i):x(xx),y(yy),id(id){}
bool operator < (const point & rhs) const{
return y < rhs.y;
}
} points[MAX];
bool cmp(const point & lhs, const point & rhs)
{
return lhs.x < rhs.x;
}
int main(void)
{
//freopen("input.txt","r",stdin);
scanf("%d",&T);
while(T--){
scanf("%d",&N);
for(int i = 0; i < N; ++i){
scanf("%lf%lf",&points[i].x,&points[i].y);
points[i].id = 0;
}
for(int i = 0; i < N; ++i){
scanf("%lf%lf",&points[i+N].x,&points[i+N].y);
points[i].id = 1;
}
sort(points,points + 2 * N,cmp);
int j = 0;
double d = 0x6f6f6f6f;
multiset<point> S;
multiset<point>::iterator it;
for(int i = 0; i < 2 * N; ++i){
double x = points[i].x, y = points[i].y;
while(j < i && (x - points[j].x > d))
S.erase(points[j++]);
for(it = S.lower_bound(point(x,y - d,0));
it != S.end() && it->y <= y + d;
++it){
double dx = x - it->x;
double dy = y - it->y;
if(it->id != points[i].id)
d = min(d,sqrt(dx * dx + dy * dy));
}
S.insert(points[i]);
}
printf("%.3f\n",d);
}
return 0;
}