Integer Intervals

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

题目大意:给定n个区间,再给出一个集合,集合中包含一些数,使得每个区间中至少有两个点在该集合中,求该集合最少包含几个数。

题目分析:
这算是区间选点问题的升级版,解法也与区间选点问题类似。
1.首先还是将区间按照右端点进行排序。
2.这个题要维护两个点(t和u,保证t>u)。因此会有两种情况:
1)a[i].l>t,说明区间与集合没有任何交点,因此要将t和u都更新t=a[i].r,u=t-1
2)a[i].l<=t&&a[i].l>u,说明区间和集合只有一个交点所以只需要更新一个点的坐标但因为要保证t>u,所以u=t,t=a[i].r
代码如下:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <set>
#include <queue>
#include <vector>
#include <string>
#include <cstring>
#include <sstream>
#include <algorithm>
#define LL long long
#define PII pair<int,int>
using namespace std;
const int N=1e4+5;
struct Node{
    int l,r;
    bool operator<(const Node &a) const//定义排序准则
    {
        return r<a.r;//按右端点进行排序
    }
}a[N];
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    cin>>a[i].l>>a[i].r;
    sort(a,a+n);
    int ans=2,t=a[0].r,u=t-1;  //初始化两个点
    for(int i=1;i<n;i++)
    {
        if(a[i].l>t)  //第一种情况
        {
            ans+=2;
            t=a[i].r;
            u=t-1;
        }
        else if(a[i].l>u) //第二种情况
        {
            ans++;
            u=t;
            t=a[i].r;
        }
    }
    cout<<ans<<endl;  //输出结果
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lwz_159

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值