G - Integer Intervals
Time Limit:1000MS Memory Limit:10000KB 64bit IO Format:%lld & %llu
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
此题是求一个区间选两个点,至少要选多少个点;区间按左端点从大到小排序,左端点相等再按右端点从大到小,如果一个大区间包含小区间,那么在小区间里的点一定也在大区间里,所以第一个区间必选,把最后两个点进行标记,遇到在两点范围内的,把前一个点替换掉,遇到在两点范围外的,两点全部替换。
<span style="font-size:14px;background-color: rgb(51, 0, 153);">#include<stdio.h>
#include<algorithm>
using namespace std;
struct note
{
int x1,x2;
}a[10010];
bool cmp(note A,note B)
{
if(A.x2 != B.x2)
return A.x2<B.x2;
return A.x1>B.x1;
}
int main()
{
int n,i;
while(~scanf("%d",&n))
{
for(i = 0;i<n;i++)
scanf("%d%d",&a[i].x1,&a[i].x2);
sort(a,a+n,cmp);
int s = 2;
int max1 = a[0].x2-1,max2 = a[0].x2;
for(i = 1;i<n;i++)
{
if(a[i].x1<=max1) continue;
else if(a[i].x1>max1 && a[i].x1<=max2)
{
max1 = max2;
max2 = a[i].x2;
s += 1;
}
else if(a[i].x1>max2)
{
max1 = a[i].x2-1;
max2 = a[i].x2;
s += 2;
}
}
printf("%d\n",s);
}
return 0;
}</span>