UVa 1615:Highway(贪心)

本文介绍了一个经典的算法竞赛题目,即如何在平面上选择最少数量的x轴上的点,以确保每个给定的点都能被一个所选的点以欧氏距离D覆盖。通过将问题转化为线段覆盖问题,并使用贪心算法进行解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=845&page=show_problem&problem=4490

给定平面上n (n105) 个点和一个值D,要求在x轴上选出尽量少的点,使得对于给定的每个点,都有一个选出的点离它的欧几里德距离不超过D。(本段摘自《算法竞赛入门经典(第2版)》)

分析:
       以给定点为圆心,D为半径画圆,与x轴交与l和r,则问题就转化成了给定x轴上的一些线段,要求用最少的点使得每个线段中至少包含一个点。可以用贪心的想法,把线段按照结束的点排序,扫描一遍就好了。

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <map>
#include <string>
#include <cmath>
#include <algorithm>
#include <sstream>

using namespace std;

const int maxn = 100005;

struct node
{
    double l, r;
    int idx;
    bool operator < (const node& right) const
    {
        return fabs(r - right.r) < 1e-8 ? (l > right.l) : (r < right.r);
    }
};

int l, n, ans;
double x, y, dx, d, pos;
node a[maxn];

int main()
{
    while (~scanf("%d%lf%d", &l, &d, &n))
    {
        for (int i = 0; i < n; ++i)
        {
            scanf("%lf%lf", &x, &y);
            dx = sqrt(d * d - y * y);
            a[i].l = x - dx;
            a[i].r = x + dx;
            a[i].idx = i;
        }
        sort(a, a + n);
        ans = 1;
        pos = a[0].r;
        for (int i = 1; i < n; ++i)
            if (a[i].l - 1e-8 < pos)
                continue;
            else
            {
                pos = a[i].r;
                ++ans;
            }
        printf("%d\n", ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值