zoukankan      html  css  js  c++  java
  • [总结] 三种常见的区间贪心问题

    一、线段覆盖

    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);
  • 相关阅读:
    本周工作量统计
    第15周个人作业
    16周第一组作业
    排球比赛积分规则
    典型用户和场景
    我和计算机
    第18周冲刺
    16周个人作业
    Java中动态获取项目根目录的绝对路径
    Spring框架下类的初始化顺序
  • 原文地址:https://www.cnblogs.com/HLXZZ/p/7261244.html
Copyright © 2011-2022 走看看