您的位置:首页 > 其它

C. Little Girl and Maximum Sum

2013-07-02 20:19 543 查看
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 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


解题说明:题目的意思是有若干对区间和的查询,问如何重组数组使查询结果的和最大。显然查询次数最多的点让他权值最大就好了,关键是怎么统计每个点的查询次数,可以用另一个数组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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: