Educational Codeforces Round 130 B. Promo

459 阅读2分钟

题目链接

题目详情

The store sells n items, the price of the i-th item is pip_i. The store's management is going to hold a promotion: if a customer purchases at least x items, y cheapest of them are free.

The management has not yet decided on the exact values of x and y. Therefore, they ask you to process q queries: for the given values of x and y, determine the maximum total value of items received for free, if a customer makes one purchase.

Note that all queries are independent; they don't affect the store's stock.

Input The first line contains two integers nn and q(1n,q2105)q (1≤n,q≤2⋅10^5) — the number of items in the store and the number of queries, respectively.

The second line contains n integers p1,p2,,pn(1pi106)p_1,p_2,…,p_n (1≤pi≤10^6), where pipi — the price of the ii-th item.

The following q lines contain two integers xix_i and yiy_i each (1yixin)(1≤y_i≤x_i≤n) — the values of the parameters x and y in the i-th query.

Output For each query, print a single integer — the maximum total value of items received for free for one purchase.

input

5 3
5 3 1 5 2
3 2
1 1
5 3

output

8
5
6

题目大意即解题思路

大意:
这家商店出售n种商品,第种商品的价格是pi。这家商店的管理层将举办一场促销活动:如果顾客购买了至少x件商品,y最便宜的商品是免费的。管理层尚未决定x和y的确切价值。因此,他们要求你处理q查询:对于给定的x和y值,如果客户进行一次购买,则确定免费收到的物品的最大总价值。请注意,所有查询都是独立的;它们不会影响商店的库存。每次查询给定x和y对于每个查询,打印一个整数-一次购买免费获得的项目的最大总价值。
解题思路:
首先我们会想到先将整个数组排序,然后从后往前就可以枚举我们要买的x个商品的价格,进而我们也可以找到这个区间里的最便宜的y项商品的价格,然后求和。但是我们看到数据量q和n都是21052·10^5时,就可以判断出会超时的(第一次做没看到),果不其然运行后会超时!!!然后这里求得又是某段区间的和,所以我们首先想到前缀和,这里我们只需找到区间的两个端点,,然后我们就可以降低时间复杂度,AC题目。

超时代码:

 while (q--)
    {
        int x, y;
        cin >> x >> y;
        int sum = 0;
        for (int i = n - x; i < n - x + y ; i++)
        {
            sum += a[i];
        }
        cout << sum << endl;
    }

AC代码

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
long long a[200010], s[200010] ;
int main()
{
    int n, q;
    cin >> n >> q;
    for (int i = 1; i <= n; i++) cin >> a[i];
    sort(a+1, a + n+1);

    for (int i = 1; i <= n; i++) 
    {
        s[i] = s[i - 1] + a[i];
    }
    while (q--)
    {
        int x, y;
        cin >> x >> y;
        long long sum = s[n - x + y ] - s[n - x];
        
        cout << sum << endl;
    }
    return 0;
}