Integer Intervals
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 14913 | Accepted: 6310 |
Description
An integer interval [a,b], a < b, is a set of all consecutive integers beginning with a and ending with b.
Write a program that: finds the minimal number of elements in a set containing at least two different integers from each interval.
Write a program that: finds the minimal number of elements in a set containing at least two different integers from each interval.
Input
The first line of the input contains the number of intervals n, 1 <= n <= 10000. Each of the following n lines contains two integers a, b separated by a single space, 0 <= a < b <= 10000. They are the beginning and the end of an interval.
Output
Output the minimal number of elements in a set containing at least two different integers from each interval.
Sample Input
4 3 6 2 4 0 2 4 7
Sample Output
4
题意:
输入n个区间,让求一个集合,每个区间至少有两个整数包含在这个集合内,求集合最少包含几个元素。
题解:
贪心。先将集合按照右边界从小到大排序。取两个变量first,second(first < second)分别为当前区间取的两个值。优先右取,这样可以保证first和second可以包含在尽量多的区间内。不断维护first和second的值。如果当前区间的左边界大于second,就需要在本区间内重新取两个值,sum+2;如果左边界小于等于second且大于first,则将second赋给first,second取右边界(保证first
< second),sum+1;如果左边界小于first,则不需要改变first和second的值。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
int left,right;
}p[10005];
bool cmp(node a,node b)
{
return a.right<b.right;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=0;i<n;i++)
scanf("%d%d",&p[i].left,&p[i].right);
sort(p,p+n,cmp);
int first=p[0].right-1,second=p[0].right,sum=2;
for(int i=1;i<n;i++)
{
if(p[i].left>second)
{
sum+=2;
second=p[i].right;
first=second-1;
}
else if(p[i].left<=second && p[i].left>first)
{
sum++;
first=second;
second=p[i].right;
}
}
printf("%d\n",sum);
}
return 0;
}