题解:B4399 [蓝桥杯青少年组国赛 2025] 第四题
省流:又是贪心。
Approach
结构体用来存这个 和 。排完序贪心,从大到小,优先让比较大的 可以用多次。
因为是结构体,所以排序注意。
Code
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n;
struct node{
int l,r;
}a[100005];
bool cmp(node x,node y){//排序,优先按首项
if(x.l!=y.l) return x.l<y.l;
else return x.r<y.r;
}
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i].l>>a[i].r;//输入
}
sort(a+1,a+n+1,cmp);//排序
int ans=0,t;//ans用来存答案,t用来代表上次用了啥
for(int i=n;i>=1;i--){//倒着遍历,贪心
//思路就是从顶上取一个(t),一直往下查
//如果t在这次的区间里
//就可以继续,否则修改t并且ans累加
if(t>=a[i].l&&t<=a[i].r){
continue;
}else{
t=a[i].l;
ans+=t;
}
}
cout<<ans;
return 0;
}但是不开long long见祖宗,所以45分。
开了long long就对了。
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n;
struct node{
int l,r;
}a[100005];
bool cmp(node x,node y){//排序,优先按首项
if(x.l!=y.l) return x.l<y.l;
else return x.r<y.r;
}
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i].l>>a[i].r;//输入
}
sort(a+1,a+n+1,cmp);//排序
int ans=0,t;//ans用来存答案,t用来代表上次用了啥
for(int i=n;i>=1;i--){//倒着遍历,贪心
//思路就是从顶上取一个(t),一直往下查
//如果t在这次的区间里
//就可以继续,否则修改t并且ans累加
if(t>=a[i].l&&t<=a[i].r){
continue;
}else{
t=a[i].l;
ans+=t;
}
}
cout<<ans;
return 0;
}