POJ 1328 Radar Installation [贪心]

#Description
一个坐标系,X轴是海岸线,上面是海,下面是大陆,海上有岛,要在海岸线上放雷达,雷达距离d,问最小放几个雷达,能全部覆盖?
#Algorithm
首先把能覆盖的海岸线区间算出来,就变成区间问题了。这次要求是最少放几个,就能把所有区间覆盖。那肯定是放头或者放尾。假设放尾,那先按尾作升序排序。第一个就是尾最小的。这个必须放,不放的话这个区间就不能覆盖。所以放这里。然后往后面找,如果区间头在这个尾前的,说明都覆盖到了。所以可行。
#Code

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 2000;
int n=0, d=0;
class V
{
public:
    double l, r;
};
bool compare(const V &a, const V &b)
{
    if (a.r < b.r) return true;
    return false;
}
int solve()
{
    V a[maxn];
    int ans = 0;
    for (int i=0; i<n; i++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        if (y>d) ans = -1;
        double r = sqrt(d*d - y*y);
        a[i].l = x - r;
        a[i].r = x + r;
    }
    if (ans == -1) return ans;
    sort(a, a+n, compare);
    int i = 0;
    do
    {
        double marked = a[i].r;
        i++;
        while (i<n&&a[i].l<=marked) i++;
        ans++;
    }while (i<n);
    return ans;
}
int main()
{
    for (int i=1;;i++)
    {
        scanf("%d%d", &n, &d);
        if (n==0 && d==0) break;
        printf("Case %d: %d\n", i, solve());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/YYecust/article/details/50812799