zoukankan      html  css  js  c++  java
  • 贪心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 } 

  • 相关阅读:
    非常牛的实现三个数交换
    assert后面如果是假则程序崩溃
    python三元操作符
    三种方法划分成绩等级
    爱因斯坦难题
    打印奇数
    判断给到的年份是否为闰年
    【bzoj1895】Pku3580 supermemo Splay
    【bzoj1050】[HAOI2006]旅行comf 并查集
    【bzoj4002】[JLOI2015]有意义的字符串 数论+矩阵乘法
  • 原文地址:https://www.cnblogs.com/Renyi-Fan/p/7135615.html
Copyright © 2011-2022 走看看