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
题目大意:找出最小的集合,使他满足给定的各个区间内至少有两个点被包括;
算法实现:贪心+标记。
解题思路:先按各个区间的尾值从小到大排序,依次扫描每个区间,确保各个区间中至少有两个点被包含在内。
参考代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct note{
int x;
int y;
};//先定义一个结构体来储存区间
struct note a[10010];
int flag[10010];//标记数组
bool cmp(note m,note n)
{
return m.y<n.y;
}
int main()
{
int t,i,j,n,m,f;
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
scanf("%d%d",&a[i].x,&a[i].y);
sort(a,a+n,cmp);
memset(flag,0,sizeof(flag));
flag[a[0].y]=1;
flag[a[0].y-1]=1;
int count=2;//所求数组的大小
for(i=0;i<n;i++)//扫描每一个数组
{
m=0;
for(j=a[i].x;j<=a[i].y;j++)
{
if(flag[j])
m++;
if(m>=2)
break;
}
if(m==0)
{
flag[a[i].y]=1;
flag[a[i].y-1]=1;
count+=2;
}
if(m==1)
{
flag[a[i].y]=1;
count+=1;
}
}
printf("%d\n",count);
}
return 0;
}