题目链接:点击打开链接
Integer Intervals
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 14497 | Accepted: 6157 |
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个区间,每个区间都是连续的int区间。
现在要在数轴上任意取一堆元素,构成一个元素集合V
要求每个区间和元素集合V的交集至少有两个不同的元素
求集合V最小的元素个数。
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n;
struct node
{
int a,b;
}s[10010];
bool cmp(node x,node y)
{
return x.b<y.b;
}
int main()
{
while(~scanf("%d",&n))
{
for(int i=0;i<n;i++)
scanf("%d%d",&s[i].a,&s[i].b);
sort(s,s+n,cmp);
int ans=2; // 点集初始数目
int r=s[0].b,l=r-1; // 集合内初始元素
for(int i=1;i<n;i++)
{
if(s[i].a>l&&s[i].a<=r) // 集合内仅有最新一个元素属于该区间
{
ans++;
l=r,r=s[i].b;
}
else if(s[i].a>r) // 集合与该区间无交集
{
ans+=2;
r=s[i].b,l=r-1;
}
}
printf("%d\n",ans);
}
return 0;
}