题解:B4399 [蓝桥杯青少年组国赛 2025] 第四题

· · 题解

题目传送门

思路

很容易想到贪心,先根据 l 从大到小排序,再根据 r从大到小排序,然后构造 p,若当前区间不包含 p,则将 p 更新为 l, 用 ans 在过程中累加 p。

注意要开 long long。

代码

#include <bits/stdc++.h>
using namespace std;

long long n, k = 1e9, ans;

struct note{
    int l, r;
}a[100005];

bool cmp(note x, note y){
    if(x.l == y.l) return x.r > y.r;
    return x.l > y.l;
}

int main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i++) cin >> a[i].l >> a[i].r;
    sort(a + 1, a + n + 1, cmp);
    for(int i = 1; i <= n; i++)
        if(a[i].r < k) k = a[i].l, ans += k;
    cout << ans << "\n";
    return 0;
}

AC记录

时间复杂度:O(n\log n)。

空间复杂度:O(n)。