题目描述:
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;
}