当前位置:网站首页>贪心(1)区间完全覆盖问题
贪心(1)区间完全覆盖问题
2022-07-29 16:00:00 【封子墨】
(1)区间完全覆盖问题
问题描述:给定一个长度为m的区间,再给出n条线段的起点和终点(注意这里是闭区间),求最少使用多少条线段可以将整个区间完全覆盖
样例:
区间长度8,可选的覆盖线段[2,6],[1,4],[3,6],[3,7],[6,8],[2,4],[3,5]
解题过程:
1将每一个区间按照左端点递增顺序排列,拍完序后为[1,4],[2,4],[2,6],[3,5],[3,6],[3,7],[6,8]
2设置一个变量表示已经覆盖到的区域。再剩下的线段中找出所有左端点小于等于当前已经覆盖到的区域的右端点的线段中,右端点最大的线段再加入,直到已经覆盖全部的区域
3过程:
假设第一步加入[1,4],那么下一步能够选择的有[2,6],[3,5],[3,6],[3,7],由于7最大,所以下一步选择[3,7],最后一步只能选择[6,8],这个时候刚好达到了8退出,所选区间为3
4贪心证明:
需要最少的线段进行覆盖,那么选取的线段必然要尽量长,而已经覆盖到的区域之前的地方已经无所谓了,(可以理解成所有的可以覆盖的左端点都是已经覆盖到的地方),那么真正能够使得线段更长的是右端点,左端点没有太大的意义,所以选择右端点来覆盖
代码如下
“`
# include< cstdio >
#include< iostream >
#include< algorithm >
#define N 100
using namespace std;
struct aa{
int l;
int r;
}a[N];
int cc(aa x,aa y);
int main()
{
int m,n,d=1,e,index=0,k=1,sum=0;
cin>>m>>n;
for(int i=0 ;i < n; i++)
cin>>a[i].l>>a[i].r;
sort(a,a+n,cc);
while(d < m)
{
e=d;
for(int i=index; i < n;i++)
{
if(a[i].l<=e)
{
if(a[i].r>=e)
{
d=a[i].r;
}
}
else
{
index=i;
break;
}
}
if(e>=d)
{
k=0;
break;
}
else
{
sum++;
}
}
if(k) cout<< sum << endl;
else cout<<”-1” << endl;
return 0;
}
int cc(aa x,aa y)
{
if(x.l==y.l)
return x.r < y.r;
else
return x.l < y.l;
}

边栏推荐
猜你喜欢

718. The longest repeat subarray

【设计师必学】在SketchUp中Enscape的灯光照明技巧

Twin all things digital visual | join the real world and the digital space

HMS Core音频编辑服务音源分离与空间音频渲染,助力快速进入3D音频的世界

【C语言刷题】Leetcode268丢失的数字

Talking about the memory layout of the program

面试突击69:TCP 可靠吗?为什么?

pycaret在钻石数据集上的使用 - 回归问题

生产者消费代码

CAS原理以及ABA问题解决Demo-代码
随机推荐
面试官:设计原则有哪些?什么是里式替换原则?
GBJ2510-ASEMI电机专用25A整流桥GBJ2510
LinkedList 5-141. 环形链表
MySQL外键约束怎么创建
新建和编辑共用一个表单,编辑之后新建,form表单resetFields失效
Moving forward steadily without forgetting the original intention, Volvo's sense of security comes from the public's recognition
Easy Genes: Human tRNA loci exhibit DNA hypermethylation associated with aging | Research Article
Staggered question explanation
Steam CMD是什么?Steam CMD怎么用?
百面量化金融
2020年Mobileye收入近10亿美元,EyeQ芯片出货1930万颗
【小程序项目开发-- 京东商城】uni-app之商品列表页面 (上)
一文参透分布式存储系统Ceph的架构设计、集群搭建(手把手)
最新!多交的税可以退,同学,你今天退税了吗?
tutorial/detailed_workflow.ipynb 量化金融Qlib库
ByteArrayOutputStream 类源码分析
This article penetrates the architecture design and cluster construction of the distributed storage system Ceph (hands-on)
Twin all things digital visual | join the real world and the digital space
【小程序项目开发--京东商城】uni-app之自定义搜索组件(上)-- 组件UI
Kubernetes 的 5 个误区