题目传送门
思路
很容易想到贪心,先根据 从大到小排序,再根据 从大到小排序,然后构造 ,若当前区间不包含 ,则将 更新为 , 用 在过程中累加 。
注意要开 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;
}时间复杂度:。
空间复杂度:。