0
点赞
收藏
分享

微信扫一扫

codeforces 276c Little Girl and Maximum Sum

双井暮色 2022-08-08 阅读 78


​​http://www.elijahqi.win/archives/1184​​​
The little girl loves the problems on array queries very much.

One day she came across a rather well-known problem: you’ve got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). You need to find for each query the sum of elements of the array with indexes from li to ri, inclusive.

The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.

Input
The first line contains two space-separated integers n (1 ≤ n ≤ 2·105) and q (1 ≤ q ≤ 2·105) — the number of elements in the array and the number of queries, correspondingly.

The next line contains n space-separated integers ai (1 ≤ ai ≤ 2·105) — the array elements.

Each of the following q lines contains two space-separated integers li and ri (1 ≤ li ≤ ri ≤ n) — the i-th query.

Output
In a single line print a single integer — the maximum sum of query replies after the array elements are reordered.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Examples
input
3 3
5 3 2
1 2
2 3
1 3
output
25
input
5 3
5 2 4 1 3
1 5
2 3
2 3
output
33

题意一开始确实看不懂,询问都给出了,为什么还有最大值

那时因为这个只是数值给定了 但是数值的顺序还可以改变所以贪心做一下就可以了

#include<cstdio>
#include<algorithm>
#define N 220000
using namespace std;
inline char gc(){
static char now[1<<16],*S,*T;
if (S==T){T=(S=now)+fread(now,1,1<<16,stdin);if (S==T) return EOF;}
return *S++;
}
inline int read(){
int x=0;char ch=gc();
while (ch<'0'||ch>'9') ch=gc();
while (ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=gc();}
return x;
}
struct node{
int x,id;
}s[N];
inline bool cmp(int a,int b){return a>b;}
inline bool cmp1(node a,node b){return a.x>b.x;}
int l[N],r[N],a[N],n,q;long long sum[N],ans;
int main(){
freopen("cf.in","r",stdin);
n=read();q=read();
for (int i=1;i<=n;++i) a[i]=read();
for (int i=1;i<=q;++i){
int l1=read(),r1=read();l[i]=l1;r[i]=r1;
s[l1].x++;s[r1+1].x--;
}
for (int i=1;i<=n;++i) s[i].x+=s[i-1].x,s[i].id=i;
sort(a+1,a+n+1,cmp);sort(s+1,s+n+1,cmp1);for (int i=1;i<=n;++i) sum[s[i].id]=a[i];
for (int i=1;i<=n;++i) sum[i]+=sum[i-1];
for (int i=1;i<=q;++i){
ans+=sum[r[i]]-sum[l[i]-1];
}
printf("%I64d",ans);
return 0;
}


举报

相关推荐

0 条评论