poj 2376 Cleaning Shifts

#include <iostream>        //区间覆盖问题--贪心
#include <algorithm>
using namespace std;
struct Node
{
int a,b;
bool operator<(const Node& other)
{
if(a!=other.a)
return a<other.a;
else
return b>other.b; //当a相等时b按从大到小,作用只有:在选择第一个区间(起点s)时选择最长的那个区间
}
}node[25002];
int main()
{
int n,t;
cin>>n>>t;
for(int i=0;i<n;++i)
scanf("%d%d",&node[i].a,&node[i].b);
sort(node,node+n);
int ok=1,ans=1;
if(node[0].a>1) //总区间[1,t]
ok=0;
else
{
int pos=node[0].b,st=0;
while(pos<t)
{
int tmp=pos;
for(;st<n&&node[st].a<=pos+1;++st) //注意这里是 pos + 1
{
if(node[st].b>tmp)
{
tmp=node[st].b; //贪心策略:选择与已确定的前一个区间有交叉且终点最远的区间
}
}
if(tmp==pos) //说明存在空白区域
{
ok=0;
break;
}
else
{
pos=tmp;
ans++;
}
}
}
if(ok)
printf("%d\n",ans);
else
printf("-1\n");

return 0;
}

posted on 2011-07-22 16:34  sysu_mjc  阅读(138)  评论(0编辑  收藏  举报

导航