题目大意:给定一个T和一些区间,用这些区间去覆盖1-T,问最少使用几个区间能将1-T完全覆盖。注意到这里[1,2]和[3,4]能将[1,4]覆盖,因为这题实际上是覆盖点。
题目链接:点击打开链接
分析:这题是贪心的一个经典模型,即贪心中的区间覆盖问题,算是比较平常的问题,所以在这里默认大家都学过,,,没学过可以百度贪心+区间覆盖问题。。其实感觉这种题更像是模拟。
附上代码:
#include<iostream> //POJ-2376
#include<algorithm>
using namespace std;
struct _pair
{
int x, y;
_pair(int a = 0, int b = 0){ x = a, y = b; }
bool operator <(const _pair &c){ return x < c.x; }
}que[25000 + 5];
int head = 0, tail = 0;
int n, T, Left = 1, Right = 1, ans;
bool flag;
inline void push(_pair v){ que[tail] = v, tail++; }
inline void pop(){ head++; }
int main()
{
scanf("%d%d", &n, &T);
for (int i = 0; i < n; i++)
{
int a, b;
scanf("%d%d", &a, &b);
push(_pair(a, b));
}
sort(que, que + n);
while (head != tail)
{
ans++;
bool ok = 0;
while (head != tail)
{
_pair t = que[head];
if (t.x <= Left) //Left表示当前需要被覆盖的区间的左边界
{
ok = 1;
if (t.y > Right) Right = t.y; //Right记录下满足t.x<=Left的所对应的最大的t.y(即最大右边界)
if (t.y >= T) goto A; //已经覆盖完成就退出
pop();
}
else break; //若不满足当前t.x<=Left了,以后t.x也必不满足
}
if (!ok) { flag = 1; break; } //若不存在t.x<=Left,即不能完全覆盖令flag=1
Left = Right + 1; //更新Left的值
}
if (Right < T) flag = 1; //区间用完了却不能完全覆盖令flag=1
A: printf("%d\n", flag ? -1 : ans);
return 0;
}