练习codeforces1697B. Promo

题目如下
B. Promo
time limit per test2 seconds
memory limit per test256 megabytes
The store sells 𝑛 items, the price of the 𝑖-th item is 𝑝𝑖. The store's management is going to hold a promotion: if a customer purchases at least 𝑥 items, 𝑦 cheapest of them are free.

The management has not yet decided on the exact values of 𝑥 and 𝑦. Therefore, they ask you to process 𝑞 queries: for the given values of 𝑥 and 𝑦, 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 𝑛 and 𝑞 (1≤𝑛,𝑞≤2⋅105) — the number of items in the store and the number of queries, respectively.

The second line contains 𝑛 integers 𝑝1,𝑝2,…,𝑝𝑛 (1≤𝑝𝑖≤106), where 𝑝𝑖 — the price of the 𝑖-th item.

The following 𝑞 lines contain two integers 𝑥𝑖 and 𝑦𝑖 each (1≤𝑦𝑖≤𝑥𝑖≤𝑛) — the values of the parameters 𝑥 and 𝑦 in the 𝑖-th query.

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

题目大意
给定数组p表示商品价格,假设购买最贵的前x个商品能够免费获得个购买商品中最便宜的y个,根据x,y计算能够获得商品的最大价值

题目分析
涉及到最贵最便宜,那么先对数组进行排序

点击查看代码
int compare(const void* a, const void* b){
    return (*(long*)b - *(long*)a);
}

qsort(p, n, sizeof(long), compare);

最便宜的y个商品可以通过前缀和对差值来计算来提高效率

点击查看代码
pre[0] = 0;
    for(int i = 1; i <= n; i++){
        pre[i] = pre[i - 1] + p[i - 1];
    }
    while(q--){
        int x, y;
        scanf("%d%d",&x,&y);
        printf("%lld\n", pre[x] - pre[x - y]);
    }

完整代码

点击查看代码
#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b){
    return (*(long*)b - *(long*)a);
}

int main(){
    int n, q;
    scanf("%d%d", &n, &q);
    long p[200005];
    long long pre[200005];
    for(int i = 0; i < n; i++){
        scanf("%ld", &p[i]);
    }
    qsort(p, n, sizeof(long), compare);
    pre[0] = 0;
    for(int i = 1; i <= n; i++){
        pre[i] = pre[i - 1] + p[i - 1];
    }
    while(q--){
        int x, y;
        scanf("%d%d",&x,&y);
        printf("%lld\n", pre[x] - pre[x - y]);
    }
    return 0;
}
posted @ 2025-07-05 21:04  sirro1uta  阅读(14)  评论(0)    收藏  举报