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;
}

 

posted @ 2016-10-17 23:05  Candy?  阅读(386)  评论(0编辑  收藏  举报