N - Little Girl and Maximum Sum——贪心

来源:互联网 发布:用友软件客服电话 编辑:程序博客网 时间:2024/06/05 00:57
Description
   

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 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 cincout streams or the %I64dspecifier.

Sample Input

3 35 3 21 22 31 3
Output
25
Input
5 35 2 4 1 31 52 32 3
Output
33
这道题的大意就是给你n个数,p次操作,

这p次操作输入l,r这个区间边界,求出区间内的值总和。但是这里有个条件是这n个数可以任意改变位置。


思路:这里我们定义一个cnt【】数组 ,表示l,r这两个点被累加了多少次,由于我们要用dp[i]=dp[i-1]+cnt[i]求出每个点被累加了多少次,所以为了防止当输入一个区间l,r时,不在区间里面的数累加,所以我们这里这样做cnt【l】++,cnt【r+1】--。

最后排个序,大的乘大的,小的乘小的,加起来就ok。

可能没有说清楚,哎,语文太差!!!!!

#include<string.h>
#include<algorithm>
#include<iostream>
#include<stdio.h>
#include<math.h>
#define mx 200009
#define LL long long 
using namespace std;
LL     a[mx];
LL    dp[mx];
LL    cnt[mx];
bool cmp(LL    x,LL    y)
{
    return x>y;
}
int main()
{


    LL    l,r;
    LL    i,j;


    LL    n,q;
    while(scanf("%lld %lld",&n,&q)!=EOF)
    {
        memset(cnt,0,sizeof(cnt));
        memset(dp,0,sizeof(dp));
        for(i=0;i<n;i++)
            scanf("%lld",&a[i]);
        while(q--)
        {
            scanf("%lld %lld",&l,&r);
            cnt[l]++;
            cnt[r+1]--;
        }
        for(i=1;i<=n;i++)
            dp[i]=dp[i-1]+cnt[i];
        LL    sum=0;
        sort(a,a+n,cmp);
        sort(dp,dp+n+1,cmp);


        for(i=0;i<n;i++)
       sum+=a[i]*dp[i];
        printf("%lld\n",sum);
    }
}


要用Long long,不然W

0 0
原创粉丝点击