跳到正文

题解

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

xuyifan2012约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年8月29日
收录
2026年8月7日
更新
2026年11月16日
篇幅
约 1 分钟
获赞
7
题目
B4399

版本

  1. v1当前

题目传送门

思路

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

注意要开 long long。

代码

C++
#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(nlog⁡n)O(n\log n)。

空间复杂度:O(n)O(n)。

原文