hihocoder-Weekly223-Interval Coverage
题目1 : Interval Coverage
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
You are given N intervals [S1, T1], [S2, T2], [S3, T3], ... [SN, TN] and a range [X, Y]. Select minimum number of intervals to cover range [X, Y].
输入
The first line contains 3 integers N, X and Y. (1 <= N <= 100000, 1 <= X < Y <= 1000000)
The following N lines each contain 2 integers Si, Ti denoting an interval. (1 <= Si < Ti <= 1000000)
输出
Output the minimum number of intevals to cover range [X, Y] or -1 if it is impossible.
-
样例输入
-
5 1 5 1 2 1 3 2 4 3 5 4 5
样例输出
-
2
题解:
参考:http://hihocoder.com/discuss/question/5567
使用贪心算法。对所有的interval上的排序之后,根据interval进行尽可能向后的选择。
#include <cstdio>
#include <cstring>
#include <cstdlib>
const int MAXN = 100000 + 10;
struct Node
{
int x, y;
}nd[MAXN];
int n, x, y;
#define max(a, b) (a)>(b)?(a):(b)
int cmp(const void *a, const void *b)
{
Node *aa = (Node *)a;
Node *bb = (Node *)b;
if(aa->x == bb->x)
{
return (aa->y - bb->y);
}
return aa->x - bb->x;
}
int main(){
scanf("%d %d %d", &n, &x, &y);
int max_y = 0;
for(int i=0; i<n; ++i)
{
scanf("%d %d", &nd[i].x, &nd[i].y);
max_y = max(max_y, nd[i].y);
}
qsort(nd, n, sizeof(Node), cmp);
if(n <= 0 || nd[0].x > x || max_y < y)
{
printf("-1\n");
}else{
int tmp_y=0, cnt = 1, start = x, end = 0;
for(int i=0; i<n; ++i)
{
if(nd[i].y < start)
{
continue;
}
if(nd[i].x <= start)
{
tmp_y = max(tmp_y, nd[i].y);
}else if(nd[i].x > end)
{
break;
}else{
start = tmp_y;
tmp_y = nd[i].y;
++cnt;
}
end = max(end, nd[i].y);
if(end >= y)
{
break;
}
}
if(end >= y)
{
printf("%d\n", cnt);
}else{
printf("-1\n");
}
}
return 0;
}