POJ 2376 Cleaning Shifts

来源:互联网 发布:网吧知乎 编辑:程序博客网 时间:2024/05/29 12:35

题意:给n个区间,求可以覆盖区间[1,n]的最少区间数,根据题干,区间[1,2]、[3,4]可以认为是可衔接的

解题思路:贪心.将n个区间的起始点和终止点用结构体存储,并按照起始点排序。如果最开始的起始点>1就输出-1,否则定义temp、nowt,选出可以与temp相连接的所有区间中终止点最大的区间,用nowt更新终止点最大的区间,找到终止点最大的区间后将nowt也就是当前的终止点赋值给temp,这一步很必要,然后在新的temp的基础上继续选择可连接的终止点最大的区间,每选出一个区间ans++

代码:

#include <iostream>#include <algorithm>#include <cstring>#include <string>#include <cstdio>#include <cmath>#include <set>using namespace std;struct P{    int st,ed;} p[25005];bool cmp(P p1,P p2){    if(p1.st==p2.st)return p1.ed<p2.ed;    return p1.st<p2.st;}int main(){    int n,t;    cin>>n>>t;    for(int i=0; i<n; i++)    {        cin>>p[i].st>>p[i].ed;    }    sort(p,p+n,cmp);    int flag=0;    if(p[0].st>1)cout<<-1<<endl;    else    {        int i=0,ans=0,nowt=0,temp=0;        while(i<n&&nowt<t)        {            ans++;            if(p[i].st>temp+1)            {                flag=1;                break;            }            else            {                while(i<n&&p[i].st<=temp+1)//找出所有可以与temp连接的最长的区间                {                    if(p[i].ed>nowt)                    {                        nowt=p[i].ed;                    }                    i++;                }                temp=nowt;            }        }        if(nowt<t||flag==1)cout<<-1<<endl;        else cout<<ans<<endl;    }    return 0;}


原创粉丝点击