• 贪心6--整数区间


    贪心6--整数区间

    一、心得

    二、题目和分析

     给n个区间,形式为[a, b],a和b均为整数,且a < b。
    求一个最小的整数点的集合,使得每个区间至少2个不同的元素(整数点)属于这个集合。
    求这个集合的元素个数。
    输入
    第1行:1个整数n(1 <= n <= 10000)
    接下来n行,每行2个整数,表示区间的左右端点a, b(0 <=a < b <= 10000)
    输出
    第1行:1个整数,表示集合的元素的个数
    样例输入
    4
    3 6
    2 4
    0 2
    4 7
    样例输出
    4

    三、代码和结果

     1 #include <iostream>
     2 #include <algorithm>
     3 using namespace std;
     4 struct act{
     5     int begin;
     6     int end;
     7 };
     8 
     9 int mycmp(const act &a,const act &b){
    10     return a.end<b.end;
    11 }
    12 
    13 //贪心,选最快结束就好 
    14 int main(){
    15     //freopen("in.txt","r",stdin);
    16     int n;
    17     cin>>n;
    18     act a[1005];
    19     for(int i=1;i<=n;i++){
    20         cin>>a[i].begin>>a[i].end;
    21     }
    22     sort(a+1,a+n+1,mycmp);
    23     cout<<"排序后的序列"<<endl; 
    24     for(int i=1;i<=n;i++){
    25         cout<<a[i].begin<<" "<<a[i].end<<endl;
    26     }
    27     int total=1;
    28     int x=a[1].end;
    29     int ans[1005];
    30     ans[total]=x;
    31     for(int i=2;i<=n;i++){
    32         if(a[i].begin>x){
    33             total++;
    34             x=a[i].end;
    35             ans[total]=x;
    36         }
    37     
    38     }
    39     cout<<"ans:"<<total<<endl;
    40     for(int i=1;i<=total;i++){
    41         cout<<ans[i]<<" ";
    42     }
    43     cout<<endl;
    44     
    45     return 0;
    46 } 

  • 相关阅读:
    ckplayer 一个不错的网页视频播放器
    onbeforeunload与a标签在IE中的冲突
    使用ckeditor 4.x 时遇到的问题及解决办法
    虚方法和重写方法的继承特性
    接口成员的访问
    基本框架(html)
    学习this关键字
    静态类
    方法参数
    Kubernetes之网络探究
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/7135615.html
Copyright © 2020-2023  润新知