首页 > 其他 > 详细

[总结] 三种常见的区间贪心问题

时间:2017-07-31 09:44:59      阅读:482      评论:0      收藏:0      [点我收藏+]

一、线段覆盖

n个开区间(ai,bi),选择尽量多个区间,使得这些区间两两不相交

右端点排序(<)兼顾左端点(>),再从左到右遇到不相交的就选

1 sort(he+1,he+n+1,cmp);
2 int tot=0,now=-1000;
3 for(int i=1; i<=n; i++) {
4   if(he[i].l>=now) now=he[i].r,tot++; 
5 }
6 printf("%d", tot);

二、区间选点

n个闭区间[ai,bi],选择尽量少的点,使得每个区间至少有一个点

右端点排序(<)兼顾左端点(>),每次选择可选区间的最后一个点

1 sort(he+1,he+n+1,cmp);
2 int tot=0,now=-1;
3 for(int i=1; i<=n; i++) {
4    if(he[i].l>now) now=he[i].r,tot++;   
5 }
6 printf("%d", tot);

三、区间覆盖

数轴上有n个闭区间[ai,bi],选择尽量少的区间覆盖一条指定的线段[s,t]

左端点排序(<)兼顾右端点(<),每次选择从当前起点能覆盖到的最长的区间

1 sort(he+1,he+n+1,cmp);
2 int tot=0,now=-1,to=-1;
3 for(int i=1; i<=n; i++) {
4   if(he[i].l<=now) to=max(to,he[i].r);
5   else now=to,to=max(he[i].r),tot++;    
6 }
7 printf("%d", tot);

 

[总结] 三种常见的区间贪心问题

原文:http://www.cnblogs.com/HLXZZ/p/7261244.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!