C-区间覆盖
题目描述
数轴上有 n (1<=n<=25000)个闭区间 [ai, bi],选择尽量少的区间覆盖一条指定线段 [1, t]( 1<=t<=1,000,000)。
覆盖整点,即(1,2)+(3,4)可以覆盖(1,4)。
不可能办到输出-1
Input:
第一行:N和T
第二行至N+1行: 每一行一个闭区间。
Output:
选择的区间的数目,不可能办到输出-1
Exmaple:
Input:
3 10
1 7
3 6
6 10
Output:
2
题目思路
这题我们使用的方法也是贪心算法,贪心准则是区间左端点的大小。在这里我们首先根据输入的数据按其左端点升序排序。然后在所有的区间中如果最小的左端点小于1就可以直接得到不可以覆盖,输出-1;否则将需要覆盖的起点left赋值为初始起点(即1),然后遍历区间,如果区间的左端点小于等于起点,并且它的右端点大于maxright则更新maxright。否则更新起点为maxright+1,此时再接着判断区间的左端点和left的大小关系,判断区间的连接是否中断如果没有中断则更新maxright,只要maxright大于等于T的时候就可以得到ans,如果最后的maxright小于T则表示无法覆盖,输出-1。
代码实现
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct section{
int a , b;
bool operator < (const section& s)const{ //升序
return a < s.a;
}
};
int n , T , ans;
int main()
{
while(scanf("%d%d",&n,&T) != EOF)
{
section t[n];
for(int i = 0; i < n; i++)
scanf("%d%d",&(t[i].a),&(t[i].b));
sort(t,t+n);
if(t[0].a > 1)
{
printf("-1\n");
return 0;
}
else
{
ans = 1;
int right = 1;
int left = 1;
int maxright = 1; //左端点在起始点左边的所有区间中的最大右端点
for(int i = 0; i < n; i++)
{
if(t[i].a <= left)
{
if(maxright < t[i].b)
maxright = t[i].b;
}
else//更新起点
{
ans++;
left = maxright + 1;
if(t[i].a > left)
{
printf("-1\n");
return 0;
}
maxright = t[i].b;
}
if(maxright >= T)
{
printf("%d\n",ans);
return 0;
}
}
if(maxright < T)
printf("-1\n");
}
}
}
总结
在这个题目中由于输入的数据较多,我们需要使用scanf读入数据而不能使用cin,否则肯能会TL,这里我们可以知道scanf需要的时间比cin要少很多,所以尽量使用scanf。另外也可以使用快速读入的方法。