基于贪心算法的区间问题

参考

区间完全覆盖问题

贪心策略:先按左界排序,然后每次都选择左界在当前覆盖范围内,右界相对最大的区间,并更新覆盖范围。

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1005;

typedef pair<int, int> P;
P a[maxn];

void solve(int n)
{
    int cnt = 0;
    sort(a, a+n);
    int maxb = a[n-1].second, cover = a[0].first, index = 0;
    while (cover < maxb)
    {
        int nowMax = 0;
        //找到当前能覆盖的,且右界最大的区间
        while(index < n)
        {
            if (a[index].first > cover) break; 
            if (a[index].first <= cover)
            {
                if (a[index].second > nowMax)
                    nowMax = a[index].second;
            }
            index++;
        }
        //延伸右界
        cover = nowMax;
        cnt++;
    }
    cout << cnt << endl;
}

int main()
{
    //freopen("./input.txt", "r", stdin);
    int n;
    cin >> n;
    for (int i = 0; i<n; ++i)
        scanf("%d,%d", &a[i].first, &a[i].second);
    solve(n);
}

最大不相交区间数

贪心算法 - Lecholin的博客 - 博客频道 - CSDN.NET

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值