Ural 1303 Minimal Coverage(贪心)

本文介绍了解决Ural1303区间覆盖问题的方法,通过将线段按左端点排序,并使用贪心算法选择尽可能向右延伸的线段,最终实现从左到右完全覆盖整个区间。

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

题目地址:Ural 1303

先按每一个线段的左端点排序,然后设置一个起点s。每次都从起点小于等于s的线段中找到一个右端点最大的。

并将该右端点作为新的起点s,然后继续找。

从左到右扫描一遍就可以。

代码例如以下:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <algorithm>

using namespace std;
#define LL __int64
const int INF=0x3f3f3f3f;
int a[100000];
struct node
{
    int l, r, ll, rr;
} fei[100000];
int cmp(node x, node y)
{
    return x.l<y.l;
}
int main()
{
    int m, i, j, n, l, r, s, max1, cnt=0, tot, pos, flag, flag1, ll, rr;
    scanf("%d",&m);
    while(scanf("%d%d",&ll, &rr)!=EOF&&(ll||rr))
    {
        if(rr<=0||ll>=m) continue ;
        fei[cnt].ll=ll;
        fei[cnt].rr=rr;
        l=ll;r=rr;
        if(l<0)
            l=0;
        if(r>m)
            r=m;
        fei[cnt].l=l;
        fei[cnt++].r=r;
    }
    sort(fei,fei+cnt,cmp);
    s=0;
    tot=0;
    if(cnt==0)
    {
        printf("No solution\n");
    }
    else
    {
        for(i=0; i<cnt;)
        {
            max1=-1;
            flag=0;
            while(fei[i].l<=s&&i<cnt)
            {
                flag=1;
                if(max1<fei[i].r)
                {
                    max1=fei[i].r;
                    pos=i;
                }
                i++;
            }
            if(!flag)
                break;
            if(s<max1)
            {
                a[tot++]=pos;
                s=max1;
            }
        }
        if(i<cnt||s<m)
            puts("No solution");
        else
        {
            printf("%d\n",tot);
            for(i=0; i<tot; i++)
            {
                printf("%d %d\n",fei[a[i]].ll,fei[a[i]].rr);
            }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值