poj2376 Cleaning Shifts 贪心

来源:互联网 发布:联合证券交易软件下载 编辑:程序博客网 时间:2024/05/21 14:44
poj2376 Cleaning Shifts 贪心

问最少选多少个区间能包含整个区间。

如果一个区间包含另一个区间,那么那个区间就没有作用。
先处理这些区间,使得后一个区间的起始值大于前一个区间的起始值,区间的结束值大于前一个区间的结束值。

再用一个结束值递增的栈,对于每个区间,如果这个区间和栈次顶的区间能相连,能包含栈顶的区间,那么栈顶区间无用,弹出。
最后栈中元素个数就是包含整个区间最小的区间数量。

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define NN 25100struct cow{int s,e;}c[NN];cow sta[NN];bool cmp(cow a,cow b){    if (a.e==b.e) return a.s<b.s;    else return a.e<b.e;}int main(){    int n,t,p,i,top,fl,ts;    while(scanf("%d%d",&n,&t)!=EOF){        for(i=1;i<=n;++i){            scanf("%d%d",&c[i].s,&c[i].e);        }        sort(c+1,c+n+1,cmp);        p=1;        for(i=2;i<=n;++i){            while (p>0&&(c[i].s<c[p].s||(c[i].s==c[p].s&&c[i].e>c[p].e))) --p;            if (c[i].e!=c[i-1].e) c[++p]=c[i];        }        n=p;        top=0;        fl=1;        cow cc;        cc.s=cc.e=0;        sta[0]=cc;        for(i=1;i<=n;++i){            ts=c[i].s-1;            while (top>=1&&sta[top-1].e>=ts) top--;            if (sta[top].e<ts) {fl=0;break;}            sta[++top]=c[i];        }        if (sta[top].e<t) fl=0;        if (fl)            printf("%d\n",top);        else puts("-1");    }    return 0;}


0 0
原创粉丝点击