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.
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 the minimal number of elements in a set containing at least two different integers from each interval.
4 3 6 2 4 0 2 4 7
4
给出数轴上的n个区间,每个区间都是连续的int区间。
现在要在数轴上任意取一堆元素,构成一个元素集合V
要求每个区间和元素集合V的交集至少有两个不同的元素
求集合V最小的元素个数。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
int x;
int y;
}p[11000];
int cmp(node a,node b)
{
if(a.y==b.y) return a.x>b.x;
else return a.y<b.y;
}
int main()
{
int n,sum=2,a,b,i;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d%d",&p[i].x,&p[i].y);
sort(p,p+n,cmp);
a=p[0].y-1;
b=p[0].y;
for(i=1;i<n;i++)
{
if(b<p[i].x)
{
sum=sum+2;
a=p[i].y-1;
b=p[i].y;
}
if(a<p[i].x&&b>=p[i].x)
{
sum=sum+1;
a=b;
b=p[i].y;
}
if(a>=p[i].x&&b>=p[i].x)
continue;
}
printf("%d\n",sum);
}