【PAT_1037】 Magic Coupon (25)

本文介绍了一种解决魔法店优惠券问题的算法,通过合理搭配优惠券与商品,实现利益最大化。具体策略包括对优惠券及商品进行分类并排序,以确保正负值匹配得当。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

The magic shop in Mars is offering some magic coupons. Each coupon has an integer N printed on it, meaning that when you use this coupon with a product, you may get N times the value of that product back! What is more, the shop also offers some bonus product for free. However, if you apply a coupon with a positive N to this bonus product, you will have to pay the shop N times the value of the bonus product... but hey, magically, they have some coupons with negative N's!

For example, given a set of coupons {1 2 4 -1}, and a set of product values {7 6 -2 -3} (in Mars dollars M$) where a negative value corresponds to a bonus product. You can apply coupon 3 (with N being 4) to product 1 (with value M$7) to get M$28 back; coupon 2 to product 2 to get M$12 back; and coupon 4 to product 4 to get M$3 back. On the other hand, if you apply coupon 3 to product 4, you will have to pay M$12 to the shop.

Each coupon and each product may be selected at most once. Your task is to get as much money back as possible.

输入

第一行:nc(优惠券的个数)
第二行:nc个优惠券的整数
第三行:np(产品的个数)
第四行:np个产品价值的整数

输出:

能得到的钱的最大值

解题思路

本题实际上当优惠券值c和产品价值p
的符号一致时能得到pc的钱,如果符号不一致则需要向商家支付|pc|。因此将优惠券和产品价值按正负值分别存入数组,然后按绝对值排序,将产品的正(负)值数组和优惠券的正(负)值数组值挨个相乘得到值v,累加v,得到最大结果。

代码

#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
static int cmp1(int a, int b) {
    return a >b;
}
int main() {
    int nc, np;
    vector<int>pcoupons, ncoupons,pproduct,nproduct;
    int t;
    scanf("%d", &nc);
    for (int i = 0; i < nc; i++) {
        scanf("%d", &t);
        if (t > 0)pcoupons.push_back(t);
        else if(t<0){
            ncoupons.push_back(t);
        }
    }
    scanf("%d", &np);
    for (int i = 0; i < np; i++) {
        scanf("%d", &t);
        if (t > 0)pproduct.push_back(t);
        else if (t<0) {
            nproduct.push_back(t);
        }
    }
    sort(pcoupons.begin(), pcoupons.end(), cmp1);
    sort(pproduct.begin(), pproduct.end(), cmp1);
    sort(nproduct.begin(), nproduct.end());
    sort(ncoupons.begin(), ncoupons.end());
    int res = 0;
    for (int i = 0; i < pcoupons.size() && i < pproduct.size(); i++) {
        res += pproduct[i] * pcoupons[i];
    }
    for (int i = 0; i < ncoupons.size() && i < nproduct.size(); i++) {
        res += ncoupons[i] * nproduct[i];
    }
    printf("%d", res);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值