time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
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.
Sample test(s)input
3 35 3 21 22 31 3
output
25
input
5 35 2 4 1 31 52 32 3
output
33
解題說明:題目的意思是有若干對區間和的查詢,問如何重組數組使查詢結果的和最大。顯然查詢次數最多的點讓他權值最大就好了,關鍵是怎麼統計每個點的查詢次數,可以用另一個數組t來存放每個點的查詢次數,每次輸入l和r讓,t[l-1]++,t[r]++,不要忘記這是區間,我們只統計了開頭和結尾,中間的部分也需要統計,於是t[i]+=t[i-1]。對原數組a和查詢次數數組t進行從小到大排序,查詢次數最多對應數值最大,這樣得到的肯定是結果最大的情況。
#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>#include <cstring>#include <string>#include<set>#include <algorithm>using namespace std;long long a[200010],t[200010],f;int main(){int n,q,l,r,i;scanf("%d %d",&n,&q); for(i=0;i<n;i++) { cin>>a[i];}sort(a,a+n); for(i=0;i<q;i++) { cin>>l>>r;t[l-1]++;t[r]--;} for(i=1;i<n;i++) {t[i]+=t[i-1];}sort(t,t+n); for(i=0;i<n;i++) {f+=a[i]*t[i];}cout<<f<<endl;return 0;}