Raid
Description After successive failures in the battles against the Union, the Empire retreated to its last stronghold. Depending on its powerful defense system, the Empire repelled the six waves of Union's attack. After several sleepless nights of thinking, Arthur, General of the Union, noticed that the only weakness of the defense system was its energy supply. The system was charged by N nuclear power stations and breaking down any of them would disable the system. The general soon started a raid to the stations by N special agents who were paradroped into the stronghold. Unfortunately they failed to land at the expected positions due to the attack by the Empire Air Force. As an experienced general, Arthur soon realized that he needed to rearrange the plan. The first thing he wants to know now is that which agent is the nearest to any power station. Could you, the chief officer, help the general to calculate the minimum distance between an agent and a station? Input The first line is a integer T representing the number of test cases. Output For each test case output the minimum distance with precision of three decimal placed in a separate line. Sample Input 2 4 0 0 0 1 1 0 1 1 2 2 2 3 3 2 3 3 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Sample Output 1.414 0.000 Source |
这个题目是平面最近点对问题,不过稍微有点不一样,这个题目在赤裸裸的最近点对上面包装了一层,开始拿到这个题目不知道怎么下手
因为上午写了一个最近点对的一个题目,所以就想用来套一下,但是感觉不怎么好用,难道要重写,重新定义结构体来重新递归分治写?
我想多了!其实这个题目稍微的要动下脑经,思维还是要开阔一下,其实这个题目可以按照我我上一篇博客写的平面最近点对问题把dis求
距离的函数改写一下,也就是如果是相同类型的点那么就认为他们的距离是无穷大,这样就避免了把两种不同的点放在一起而无法区分的
尴尬了,表示这个想法开始没想到,这个题目纠结了一会迟迟不想下手!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <iostream>
using namespace std;
#define inf 1e8
struct point
{
double x;
double y;
bool flag;
}node[200100];
int my_rec[200100];
int n;
double dis(point &a,point &b)
{
if(a.flag == b.flag)
return inf;
return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
}
int cmp(const point &a,const point &b)
{
return a.x < b.x;
}
bool cmpy(const int &a,const int &b)
{
return node[a].y < node[b].y;
}
double find_min(int l,int r)
{
int i,j,k;
double tmp;
if(l==r)
return inf;
if(l==r-1)
return dis(node[l],node[r]);
double temp1=min(find_min(l,(l+r)/2),find_min((l+r)/2,r));
int mid=(l+r)/2;
k=0;
for(i=l;i<=r;i++)
if(fabs(node[i].x - node[mid].x) < temp1)
my_rec[k++]=i;
sort(my_rec,my_rec+k,cmpy);
for(i=0;i<k-1;i++)
for(j=i+1;j<k && j<i+7;j++)
{
tmp=dis(node[my_rec[i]],node[my_rec[j]]);
if(tmp < temp1)
temp1=tmp;
}
return temp1;
}
int main()
{
int i,j,k;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%lf%lf",&node[i].x,&node[i].y);
node[i].flag=1;
}
for(i=n,n*=2;i<n;i++)
{
scanf("%lf%lf",&node[i].x,&node[i].y);
node[i].flag=0;
}
if(n==2)
{
printf("%.3lf\n",dis(node[0],node[1]));
continue;
}
sort(node,node+n,cmp);
//for(i=0;i<n;i++)
//printf("%lf\n",node[i].x);
printf("%.3lf\n",find_min(0,n-1));
}
return 0;
}