[贪心]BZOJ 3410: [Usaco2009 Dec]Selfish Grazing 自私的食草者

来源:互联网 发布:中国软件杯影响力 编辑:程序博客网 时间:2024/05/17 07:54

你没看错,这道题就是水博客的。

本题有权限……


题目大意

题目要求给出n条线段(Li,Ri),要求选出最多的线段,保证任意两条线段不会相交。


题目分析

贪心的思路,假设目前求出一个值lst,表示最后一条线段的R值,然后对于一条新入的线段,如果lst<=L,说明可以容下,那就把这道线段加入答案中,更新lst,但如果不行,那怎么办?仔细思考后发现依旧贪心思路,把当前答案中最后一条线段剔除,然后加入这条线段,这样可以挪出更多的空间给接下来的牛。

复杂度

时间:O(n*logn)(别忘记排序); 空间:O(n)


代码

#include<cstdio>#include<algorithm>using namespace std;struct data{    int x,y;    bool operator < (const data b)const{        return x<b.x||(x==b.x&&y<b.y);    }}a[50005];int n,ans,lst;inline void readi(int &x){    x=0; char ch=getchar();    while ('0'>ch||ch>'9') ch=getchar();    while ('0'<=ch&&ch<='9') {x=x*10+ch-'0'; ch=getchar();}}int main(){    freopen("glass.in","r",stdin);    freopen("glass.out","w",stdout);    readi(n);    for (int i=1;i<=n;i++) {readi(a[i].x); readi(a[i].y);}    ans=lst=0; sort(a+1,a+n+1);    for (int i=1;i<=n;i++)        if (lst<=a[i].x) {lst=a[i].y; ans++;}        else if (a[i].y<lst) lst=a[i].y;    printf("%d",ans);    return 0;}
阅读全文
0 0