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.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
给出一组区间,找出一组数,使每个区间中至少有两个数在这组数中。
思路:
这和课上讲的差不多都是贪心做,先将该区间按区间[a,b]中b作为排序,用一个数组标记该组数是否有此数,然后对每一个区间遍历,看此区间中有几个数,1,没有就选取区间最后两个数,2,有一个数,选取区间最后一个数。3,有两个数则不用管。累加统计被标记数。
#include <iostream>
#include <algorithm>
#include<stdio.h>
#include<vector>
#include<string.h>
#include<string>
using namespace std;
struct code
{
int x,y;
}a[10001];
bool cmp(code j,code k)
{
if(j.y!=k.y)return (j.y<k.y);
else return (j.x<k.x);
}
int main()
{
int b[10001],cnt=0,sum=0,n;
memset(b,0,sizeof(b));
cin>>n;
for(int i=0;i<n;i++)
{cin>>a[i].x>>a[i].y;}
sort(a,a+n,cmp);
b[a[0].y]=1;
b[a[0].y-1]=1;
cnt=2;
for(int i=1;i<n;i++)
{
sum=0;
for(int j=a[i].x;j<=a[i].y;j++)
{
if(b[j])sum++;
if(sum==2)break;
}
if(sum==1)
{
b[a[i].y]=1;
cnt++;
}
if(sum==0)
{
b[a[i].y]=1;
b[a[i].y-1]=1;
cnt=cnt+2;
}
}
cout<<cnt;
}