Integer Intervals

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.

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值