codeforces276C

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 nelements (the elements of the array are indexed starting from 1); also, there are qqueries, each one is defined by a pair of integers liri (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


正解是线段树,不过也有一种有趣的方法,计算每个点出现次数,将两个数组排序相乘即可
 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<iostream>
 4 #include<algorithm>
 5 #include<string.h>
 6 using namespace std;
 7 const int maxn = 21000;
 8 const int inf = 0x7f7f7f7f;
 9 const int mod = 1e9 + 7;
10 typedef long long ll;
11 typedef unsigned long long ull;
12 int n,q;
13 int a[maxn];
14 int b[maxn];
15 int main()
16 {
17     ios::sync_with_stdio(false);
18     cin>>n>>q;
19     for(int i=1;i<=n;i++)
20         cin>>a[i];
21     sort(a+1,a+1+n);
22     memset(b,0,sizeof(b));
23     int L,R;
24     for(int i=1;i<=n;i++){//神奇的求某个点的被加次数方法 
25         cin>>L>>R;
26         b[L]++;
27         b[R+1]--;
28     }
29     for(int i=1;i<=n;i++)
30         b[i]+=b[i-1]; 
31     sort(b+1,b+1+n);
32     ll ans=0;
33     for(int i=1;i<=n;i++)
34         ans+=a[i]*b[i];
35     cout<<ans<<endl;
36     return 0;
37  } 

猜你喜欢

转载自www.cnblogs.com/zy-18-yz/p/9992066.html