POJ 1328 Radar Installation 贪心

来源:互联网 发布:linux运行我的世界 编辑:程序博客网 时间:2024/05/22 17:07

题目大意:

以x轴为海岸线,x轴上方为海洋,x海中的岛屿视为点,给出雷达探测半径d和所有岛屿的坐标,为最少需要多少个建在海岸线上的雷达使得所有的岛屿都被覆盖,输出最少需要的雷大数,若不可能全部覆盖,输出-1


大致思路:

首先对于每个岛屿,如果其中坐标大于d则不可能被覆盖到,输出-1

否则对于每个岛屿都可以在海岸线上对应一段位置,该位置内建造雷达都可以覆盖到它

那么对于n个雷达对应的线段或点状区域,按左端点排列,如果相邻的两条线段中,第二条线段的左端点在第一条线段内,右端点不在,则雷达放在第一条线段右端点处不变,若是第二条线段被第一条覆盖,则雷达位置变为第二条线段右端点,若是第二条线段与第一条无交点,都位于第一条线段的右边,则需要添加一个新雷达放置在第二条线段的右端点处,这样一直到最后一条线段,就能得到最终需要的最小雷达数


代码如下:

Result   : Accepted      Memory   :   192 KB     Time  :  32 ms

/* * Author: Gatevin * Created Time:  2014/7/16 13:47:54 * File Name: test.cpp */#include<iostream>#include<sstream>#include<fstream>#include<vector>#include<list>#include<deque>#include<queue>#include<stack>#include<map>#include<set>#include<bitset>#include<algorithm>#include<cstdio>#include<cstdlib>#include<cstring>#include<cctype>#include<cmath>#include<ctime>#include<iomanip>using namespace std;const double eps(1e-8);typedef long long lint;int n,d;int sgn(double d){    return d < -eps ? -1 : (d > eps ? 1 : 0);}struct segment{    double left;    double right;    bool operator < (const segment& s) const    {        return sgn(left - s.left) == -1;    }};segment seg[1010];int main(){    int x,y;    int cas = 0;    int answer;    double now;    bool flag;    while(scanf("%d %d",&n,&d) == 2)    {        if(n == 0 && d == 0) return 0;        cas++;        flag = false;        for(int i = 1; i <= n; i++)        {            scanf("%d %d",&x,&y);            if(y > d)//找不到符合条件雷达的点            {                flag = true;            }            else            {            seg[i].left = x - sqrt(d*d - y*y*1.0);            seg[i].right = x + sqrt(d*d - y*y*1.0);            }        }        if(flag)        {            printf("Case %d: -1\n",cas);            goto nex;        }        sort(seg + 1, seg + n + 1);        now = seg[1].right;        answer = 1;        for(int i = 2; i <= n; i++)//贪心        {            if(sgn(seg[i].right - now) <= 0)            {                now = seg[i].right;                continue;            }            else            {                if(sgn(seg[i].left - now) <= 0)                {                    continue;                }                else                {                    answer++;                    now = seg[i].right;                }            }        }        if(n == 0)        {            printf("Case %d: 0\n",cas);        }        else        {            printf("Case %d: %d\n",cas,answer);        }        nex : ;    }    return 0;}


0 0
原创粉丝点击