Little Girl and Maximum Sum CodeForces - 276C

Posted 啦啦啦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Little Girl and Maximum Sum CodeForces - 276C相关的知识,希望对你有一定的参考价值。

---恢复内容开始---

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.

Example

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

题意:给一个数列,和q次询问,在回答询问之前,对数列重新排一次序,使得q次询问的和最大。
题解:先计算出所有询问中每个下标出现的次数,出现次数多的就把数列中的较大值分配给它。重点在于计算下标出现的次数!
 1 #include<cmath>
 2 #include<cstdio>
 3 #include<string>
 4 #include<cstring>
 5 #include<iostream>
 6 #include<algorithm>
 7 using namespace std;
 8 typedef long long ll;
 9 
10 const int maxn=200005;
11 
12 int n,m;
13 int a[maxn],q[maxn],s[maxn];
14 
15 int main()
16 {   int l,r;
17     cin>>n>>m;
18     for(int i=1;i<=n;i++){
19         q[i]=0,s[i]=0;
20         scanf("%d",&a[i]);
21     }
22     for(int i=1;i<=m;i++){          //
23         scanf("%d%d",&l,&r);
24         q[l]++,q[r+1]--;
25     }                                  一个叫差分数列的东西
26     s[0]=0;
27     for(int i=1;i<=n;i++)
28         s[i]=s[i-1]+q[i];           //
29     sort(a+1,a+n+1);
30     sort(s+1,s+n+1);
31     ll sum=0;
32     for(int i=1;i<=n;i++) sum+=(long long)a[i]*s[i];    //不用long long 的话可能溢出!
33     cout<<sum<<endl;
34 }

 

---恢复内容结束---

以上是关于Little Girl and Maximum Sum CodeForces - 276C的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces Round #169 (Div. 2)C. Little Girl and Maximum Sum

C. Little Girl and Maximum Sum差分 / 贪心

D. Little Girl and Maximum XOR(贪心)

CF276E Little Girl and Problem on Trees 题解

B. Little Girl and Game1300 / 回文字符串 博弈论

codeforces 686B B. Little Robber Girl's Zoo(水题)