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个区间的最后两个元素x和y
若第i+1个区间包含了这两个元素,则跳到下一个区间所取的元素个数+0
若第i+1个区间只包含了这两个元素中的一个(由于有序,所以必定是包含y),则取第i+1个区间的最后一个元素,所取的元素个数+1。为了方便下一区间的比较,更新x和y的值,使他们为当前V集合中最后的两个元素。
若第i+1个区间没有包含这两个元素,则第i+1个区间的最后两个元素,所取的元素个数+2。为了方便下一区间的比较,更新x和y的值,使他们为当前V集合中最后的两个元素。
元素初值初始化为2
x初始化为第一个区间的最后倒数第2个元素
y初始化为第一个区间的最后的元素
#include<stdio.h>
#include<algorithm>
using namespace std;
struct F
{
int a,b;
} s[10010];
int cmp(F x,F y)
{
return x.b<y.b;
}
int main()
{
int n,i,j,x,y;
scanf("%d",&n);
for(i=0; i<n; i++)
scanf("%d%d",&s[i].a,&s[i].b);
sort(s,s+n,cmp);
j=2;
x=s[0].b-1;
y=s[0].b;
for(i=1; i<n; i++)
{
if(s[i].a<=x&&s[i].b>=y)//如果此区间包含了这两个元素,不用再取
continue;
if(s[i].a<=y&&s[i].a>x)//如果只包含一个,肯定是y
{
x=y;
y=s[i].b;//更新x和y
j+=1;//增加一个元素
}
if(s[i].a>y)//如果不包含任意一个元素,就需要增加后两位元素
{
x=s[i].b-1;//更新元素的值
y=s[i].b;//因为数据是从小到大排的额,所以保存后两位
j+=2;//元素数量加2
}
}
printf("%d\n",j);
return 0;
}