[C++][算法基础]最大不相交区间数量(贪心 + 区间问题2)

给定 𝑁 个闭区间 𝑎𝑖,𝑏𝑖,请你在数轴上选择若干区间,使得选中的区间之间互不相交(包括端点)。

输出可选取区间的最大数量。

输入格式

第一行包含整数 𝑁,表示区间数。

接下来 𝑁 行,每行包含两个整数 𝑎𝑖,𝑏𝑖,表示一个区间的两个端点。

输出格式

输出一个整数,表示可选取区间的最大数量。

数据范围

1≤𝑁≤,

≤𝑎𝑖≤𝑏𝑖≤

输入样例:
复制代码
3
-1 1
2 4
3 5
输出样例:
复制代码
2

代码:

cpp 复制代码
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

const int N = 100010;
int n,l,r;
vector<pair<int,int>> Interval;

int main(){
    cin>>n;
    for(int i = 0;i < n;i ++){
        cin>>l>>r;
        Interval.push_back({r,l});
    }
    sort(Interval.begin(),Interval.end());
    int res = 0, RightEnd = -2e9;
    for(int i = 0;i < n;i ++){
        int left = Interval[i].second;
        int right = Interval[i].first;
        if(left > RightEnd){
            res ++;
            RightEnd = right;
        }
    }
    cout<<res<<endl;
    return 0;
}
相关推荐
phltxy1 小时前
C语言操作符详解
java·c语言·算法
RuoZoe2 小时前
从 2026 年 3 月 1 日开源,到 26.10.9:Jalium UI 半年时间到底走了多远?
c语言·c++
aqiu1111112 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye3 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考3 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
鱼子星_3 小时前
【C++】继承和多态(上)
c++·笔记
玖玥拾4 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研5 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
郝学胜-神的一滴5 小时前
Qt 高级编程 045:坐标体系深度实战
开发语言·c++·windows·python·qt·程序人生