https://pintia.cn/problem-sets/994805342720868352/problems/994805451374313472
1037 Magic Coupon (25 分)
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.
Output Specification:
For each test case, simply print in a line the maximum amount of money you can get back.
Sample Input:
4
1 2 4 -1
4
7 6 -2 -3
Sample Output:
43
思路
注意这句话:
有些商品免费,
所以说优惠券不一定和商品数量一致,要注意免费的情况
需要分开处理 优惠券数量大于商品数量,商品数量大于优惠券数量的情况
具体先排序两个数组,
只需要取都为小于0的数字,相乘,然后把还有小于0的元素的那个组遍历一下
再从最大的数开始往回遍历,直到遍历到其中一个数组先遍历完;
如果这时还有商品,可以直接获利,这部分需要加上
#include <iostream>
#include<algorithm>
using namespace std;
//Magic Coupon
int GetMaxIncome(int nCoupons, int* coupons, int nProduct, int* products) {
sort(coupons, coupons + nCoupons);
sort(products, products + nProduct);
int idCoupon = 0, idProduct = 0;
int income = 0;
while (idCoupon < nCoupons && idProduct < nProduct)
{
if (coupons[idCoupon] < 0 && products[idProduct] < 0)
{
income += coupons[idCoupon] * products[idProduct];
}
else {
while (idCoupon < nCoupons && coupons[idCoupon]<0)
{
idCoupon++;
}
while (idProduct<nProduct&& products[idProduct]<0)
{
idProduct++; // 免费给
}
break;
}
idCoupon++;
idProduct++;
}
int ridCoupon = nCoupons - 1;
int ridProduct = nProduct - 1;
while (ridCoupon >= idCoupon && ridProduct >= idProduct)
{
if (coupons[ridCoupon] > 0 && products[ridProduct] > 0)
{
income += coupons[ridCoupon] * products[ridProduct];
}
else {
while (ridCoupon > idCoupon && coupons[ridCoupon] >0 )
{
idCoupon--;
}
while (ridProduct > nProduct && products[ridProduct] > 0)
{
idProduct--;
income += products[ridProduct];
}
break;
}
ridCoupon--;
ridProduct--;
}
return income;
}
int main()
{
int nCoupons = 0, nProduct = 0;
cin >> nCoupons;
int* coupons = new int[nCoupons];
for (int i = 0; i < nCoupons; i++)
{
cin >> coupons[i];
}
cin >> nProduct;
int* products = new int[nProduct];
for (int i = 0; i < nProduct; i++)
{
cin >> products[i];
}
cout << GetMaxIncome(nCoupons, coupons, nProduct, products);
}