poj 2376 Cleaning Shifts

本文讨论了使用贪心算法解决区间覆盖问题的方法,包括定义了一个结构体Node来表示区间,并通过排序和选择策略找到覆盖整个目标区间[1,t]的最少数量的不重叠区间。
#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;
}

转载于:https://www.cnblogs.com/mjc467621163/archive/2011/07/22/2114081.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值