【贪心】URAL - 1303 Minimal Coverage

Step1 Problem:

给你一系列闭合区间(以0 0结束),求[0,M]至少需要几个区间可以将其包含,输出区间个数 和 区间(按左边界从小到大)。
数据范围:
1<= M <=5000, -50000 <= Li < Ri <= 50000.

Step2 Involving algorithms:

贪心

Step3 Ideas:

假设我们要包含,[0,0]这个区间,需要的区间左边界肯定得<=0,右边界越大越好。
右边界大的 效果一定比 右边界小的好,因为作用域大。
对于[0,0]这个区间,例如[-2, 1] 和 [-1, 2]这个两个区间作用域分别为[0, 1], [0, 2],右区间大的 作用域大。
所以一开始[0,0]我们找到满足的右边界最大lmax后,[0,0]更新为[lmax, lmax]继续查找就好了。

Step4 Code:

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
struct node
{
    int lt, rt;
    bool operator < (const node &b) const {
        if(lt == b.lt) return rt < b.rt;
        else return lt < b.lt;
    }
};
node a[N];
int ans[N];
int main()
{
    int pos, u, v;
    scanf("%d", &pos);
    int top = 0;
    while(~scanf("%d %d", &u, &v))
    {
        if(!u && !v) break;
        if(v <= 0 || u > pos) continue;
        a[top++] = (node){u, v};
    }
    sort(a, a + top);
    int lpos = 0, top1 = 0;
    for(int i = 0; lpos < pos && i < top; )
    {
        int Max = lpos, ma;
        if(a[i].lt > lpos) break;
        while(a[i].lt <= lpos && i < top)
        {
            if(Max < a[i].rt) {
                Max = a[i].rt;
                ma = i;
            }
            i++;
        }
        if(Max != lpos) {
        lpos = Max;
        ans[top1++] = ma;
        }
    }
   // printf("%d\n", top1);
    if(lpos < pos) {
        printf("No solution\n");
    } else {
        printf("%d\n", top1);
        for(int i = 0; i < top1; i++)
            printf("%d %d\n", a[ans[i]].lt, a[ans[i]].rt);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值