POJ1328---Radar Installation(贪心算法)

刚开学的时候,课程设计的时候写过这道题,当时用c写的,排序用的选择排序,现在用c++写了下,用的快排,哇,惊人的发现在oj上后者比前者慢一倍,c的输入输出这么快的吗?
本题贪心算法里面的区间问题。思路:
计算小岛的雷达安装范围,对全部的安装范围按照左端点进行排序,然后从左到右,如果两个区间有交叉,不用安装;如果包含,更新右端点;如果没有交点,安装雷达,更新右端点。

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
using namespace std;
struct point
{
    double left, right;
};
point a[1005];
bool cmp(point a, point b)
{
    return a.left < b.left;
}

int main()
{
    int n, r;
    int num = 0;//输入数据次数
    int count;//雷达数量
    int x, y;//接受横纵坐标
    while (cin >> n >> r, n || r)
    {
        num++;
        bool flag = true;
        for (int i = 0; i < n; i++)
        {
            cin >> x >> y;
            if (y > r)flag = false;
            else
            {
                double d = sqrt(r*r - y*y);
                a[i].left = x*1.0 - d;
                a[i].right = x*1.0 + d;
            }
        }
        if (!flag)
            cout << "Case " << num << ": -1" << endl;
        else
        {
            sort(a, a + n,cmp);
            double s = a[0].right; count = 1;
            for (int i = 1; i < n; i++)
            {
                if (a[i].left > s)   //没有交点的时候,安装雷达
                {
                    count++;
                    s = a[i].right;
                }
                else if (a[i].right < s)  //前者包含后者的时候,更新右端点;
                    s = a[i].right;
                //交叉什么也不用做

            }
            cout << "Case " << num << ": ";
            cout << count << endl;
        }

    }
    system("pause");
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值