码迷,mamicode.com
首页 > 其他好文 > 详细

Little Girl and Maximum Sum CodeForces - 276C

时间:2017-07-31 01:10:50      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:tin   sample   order   this   color   contain   define   each   problem   

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

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

标签:tin   sample   order   this   color   contain   define   each   problem   

原文地址:http://www.cnblogs.com/zgglj-com/p/7261001.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!