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
大致题意:
给出数轴上的n个区间,每个区间都是连续的int区间。
现在要在数轴上任意取一堆元素,构成一个元素集合V
要求每个区间和元素集合V的交集至少有两个不同的元素
求集合V最小的元素个数。
解题思路:贪心算法
先对所有区间按末端点排序
取第i个区间的最后两个元素Selem和Eelem
若第i+1个区间包含了这两个元素,则跳到下一个区间所取的元素个数+0
若第i+1个区间只包含了这两个元素中的一个(由于有序,所以必定是包含Eelem),则取第i+1个区间的最后一个元素,所取的元素个数+1。为了方便下一区间的比较,更新Selem和Eelem的值,使他们为当前V集合中最后的两个元素。
若第i+1个区间没有包含这两个元素,则第i+1个区间的最后两个元素,所取的元素个数+2。为了方便下一区间的比较,更新Selem和Eelem的值,使他们为当前V集合中最后的两个元素。
Selem初始化为第一个区间的最后倒数第2个元素
Eelem初始化为第一个区间的最后的元素
所取的元素个数初始化为2 (就是Selem和Eelem)
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
int l,r;
} a[10010];
bool cmp(node A,node B)
{
if(A.r!=B.r)
return A.r<B.r;
else return A.l>B.l;
}
int main()
{
int i,n,t,t1,t2;
while(~scanf("%d",&n))
{
memset(a,0,sizeof(a));
for(i=0; i<n; i++)
scanf("%d%d",&a[i].l,&a[i].r);
sort(a,a+n,cmp);
int s=2,t1=a[0].r,t2=a[0].r-1;
for(i=1;i<n;i++)
{
if(t2>=a[i].l)
continue;
else if(t2<a[i].l&&t1>=a[i].l)
{
t2=a[i].r;
s++;
}
else if(t2<a[i].l&&t1<a[i].l)
{
t1=a[i].r;
t2=a[i].r-1;
s+=2;
}
if(t1<t2)
{
t=t1;
t1=t2;
t2=t;
}
}
printf("%d\n",s);
}
return 0;
}