Codeforces Round 169 (Div. 2)C. Little Girl and Maximum Sum(差分、贪心)
题面
链接
C. Little Girl and Maximum Sum
题意
给q个[l,r]将所有这些区间里面的数相加和最大。
可以进行的操作是任意排列数组
题解
对出现的每个区间内的位置加上1,代表权值
操作完之后求一遍前缀和,得到每个位置的权值
然后贪心的考虑,权值越大,应该分配给该位置的数越大越好这样对答案的贡献最大。
代码
#include <bits/stdc++.h>
#define int long long
#define rep(i,a,b) for(int i = (a); i <= (b); ++i)
#define fep(i,a,b) for(int i = (a); i >= (b); --i)
#define pii pair<int, int>
#define pll pair<long long, long long>
#define ll long long
#define db double
#define endl '\n'
#define x first
#define y second
#define pb push_back
using namespace std;
const int N=2e5+10;
int a[N],cf[N];
void solve()
{
int n,q;
cin>>n>>q;
rep(i,1,n){
cin>>a[i];
}
sort(a+1,a+1+n,greater<int>());
while(q--){
int l,r;
cin>>l>>r;
cf[l]+=1,cf[r+1]-=1;
}
rep(i,1,n){
cf[i]+=cf[i-1];
}
sort(cf+1,cf+1+n,greater<int>());
int ans=0;
rep(i,1,n){
ans+=cf[i]*a[i];
}
cout<<ans<<endl;
}
signed main(){
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
// freopen("1.in", "r", stdin);
int _;
// cin>>_;
// while(_--)
solve();
return 0;
}
总结
注意空间,空间开小了在cf上可能
对着种多次区间操作,一次查询要考虑一下差分,很多时候用不到那么复杂的数据结构就能解决问题。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署