跳到正文

题解

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

DUCK_inanimated_约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
题目
B4399

版本

  1. v1当前

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

省流:又是贪心。

Approach

结构体用来存这个 lil_i 和 rir_i 。排完序贪心,从大到小,优先让比较大的 pip_i 可以用多次。
因为是结构体,所以排序注意。

Code

C++
#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就对了。

C++
#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;
}
原文