CODEVS1643 线段覆盖3[贪心]

1643 线段覆盖 3 

 

 时间限制: 2 s 
 空间限制: 256000 KB 
 题目等级 : 黄金 Gold
 
 
 
题目描述  Description

在一个数轴上有n条线段,现要选取其中k条线段使得这k条线段两两没有重合部分(端点可以重合),问最大的k为多少。

 

 

 

输入描述  Input Description

输入格式

输入文件的第1行为一个正整数n,下面n行每行2个数字ai,bi,描述每条线段。

输出描述  Output Description

输出格式

  输出文件仅包括1个整数,为k的最大值

样例输入  Sample Input

3

0 2

2 4

1 3

样例输出  Sample Output

2

数据范围及提示  Data Size & Hint

数据范围

对于20%的数据,n≤10;

对于50%的数据,n≤1000;

对于70%的数据,n≤100000;

对于100%的数据,n≤1000000,0≤ai<bi≤1000000。


 

白书

区间按r排序,然后贪心取第一个

扫一遍即可

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N=1e6+5;
inline int read(){
    char c=getchar();int x=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}
int n;
struct seg{
    int l,r;
    bool operator <(const seg &x)const{return r<x.r;}
}a[N];
int main(int argc, const char * argv[]) {
    n=read();
    for(int i=1;i<=n;i++){
        a[i].l=read(),a[i].r=read();
        //if(a[i].l>a[i].r) swap(a[i].l,a[i].r);
    }
    sort(a+1,a+1+n);
    int now=a[1].l,cnt=0;
    for(int i=1;i<=n;i++){
        if(now<=a[i].l){
            cnt++;
            now=a[i].r;
        }
    }
    printf("%d",cnt);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值