POJ 3714 Raid

来源:互联网 发布:如何用java做网站 编辑:程序博客网 时间:2024/04/30 00:51

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?


【题目分析】
平面最近点对,先按照x排序。然后二分。合并两个子问题时,先取两个子问题的最小值x,然后把切分的位置左右的点找出来(在x以内的)。
然后把这些点按照y排序。然后枚举。显然是单调的,如果超过就跳出(强力剪枝)。注意计算距离时,如果两个点在同一个子集里,返回无限大的值。
注意:一定要写%.f,写%.lf会WA的,推荐只输出一个的情况下用cout!


【代码】

#include <iostream>#include <stdio.h>#include <iomanip>#include <algorithm>#include <cmath>using namespace std;const int N=200000+1;const double INF=1e100;struct Point{    double x,y;    bool flag;};Point m[200002];int tmp[200002];double dis(Point p1,Point p2){return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));}double minL(double l1,double l2){return l1<=l2?l1:l2;}bool cmpy(int a,int b){return m[a].y<m[b].y;}bool cmpx(Point a,Point b){return a.x<b.x;}double getMinLen(Point *s,int l,int r){    double rs=INF;    if(l==r)return rs;    if(l+1==r) if(s[l].flag == s[r].flag) return rs;        else return dis(s[l],s[r]);    int mid=(l+r)/2;    rs=getMinLen(s,l,mid);    rs=minL(rs,getMinLen(s,mid+1,r));    int i,j,num=0;    for(i=l;i<=r;++i)    {if(fabs(s[i].x-s[mid].x)<=rs)tmp[num++]=i;}    sort(tmp,tmp+num,cmpy);    double d=INF;    for(i=0;i<num;++i)    for(j=i+1;j<num;++j)    {        if(fabs(s[tmp[i]].y-s[tmp[j]].y)>=rs)break;        if(s[tmp[i]].flag!=s[tmp[j]].flag && (d=dis(s[tmp[i]],s[tmp[j]]))<rs)rs=d;    }    return rs;}int main(){    int t,n,i;    scanf("%d",&t);    while(t--)    {        scanf("%d",&n);        for(i=0;i<n;++i) scanf("%lf%lf",&m[i].x,&m[i].y),m[i].flag=0;        for(i=0;i<n;++i)scanf("%lf%lf",&m[i+n].x,&m[i+n].y),m[i+n].flag=1;        n<<=1;        sort(m,m+n,cmpx);        double ans=getMinLen(m,0,n-1);        cout<<setiosflags(ios::fixed)<<setprecision(3)<<ans<<endl;    }    return 0;}
0 0
原创粉丝点击