C. Little Girl and Maximum Sum

來源:互聯網
上載者:User
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 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.

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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.