[PAT A1037]Magic Coupon
题目描述
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.
输入格式
Each input file contains one test case. For each case, the first line contains the number of coupons NC, followed by a line with NC coupon integers. Then the next line contains the number of products NP, followed by a line with NP product values. Here 1≤NC,NP≤105, and it is guaranteed that all the numbers will not exceed 230.
输出格式
For each test case, simply print in a line the maximum amount of money you can get back.
输入样例
4
1 2 4 -1
4
7 6 -2 -3
输出样例
43
解析
- 这道题目大致意思就是先输入n个数,后输入m个数,我们可以从前n个数中选一个数与后m个数中选一个数相乘,最后需要我们求最大的结果,以样例为例,我们选择4和7,2和6,-1和-3,这样加起来结果是28+12+3=43,剩下的两个数就没必要取了,因为它们相乘的结果必然会使得结果减少。
- 我的思路是将它们按升序排列,使用两个指针分别指向两个数组中最前面的数字,如果它们都是负数,那么使它们相乘,直到其中有一个为正为止;然后使两个指针都指向最后面的数,如果他们都是正数,那么使它们相乘,直到有一个为负为止。
- 这其实是贪心的策略,这样我们需要考虑的只有一种特殊情况,就是两个数组,一个全为负,一个全为正,这样我们只需要判断一下这个情况给一个输出就行了。另外不要自作聪明的使用num[i]*num[j]>0表示它们都是负数,因为在两个数组负数个数相等的时候,这样会导致出错,读者可以自己试试。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n, m;
vector<int> num1, num2; //两个数组,分别存放第一行数和第二行数
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int temp;
scanf("%d", &temp);
num1.push_back(temp);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
int temp;
scanf("%d", &temp);
num2.push_back(temp);
}
sort(num1.begin(), num1.end()); //按升序排序
sort(num2.begin(), num2.end());
int i = 0, j = 0, ans = 0;
while (num1[i] < 0 && num2[j] < 0) {
ans += num1[i] * num2[j];
i++; j++;
}
i = n - 1; j = m - 1;
while (num1[i] > 0 && num2[j] > 0) {
ans += num1[i] * num2[j];
i--; j--;
}
if (ans == 0)ans += (num1[0] * num2[m - 1] > num1[n - 1] * num2[0]) ? num1[0] * num2[m - 1] : num1[n - 1] * num2[0];
printf("%d", ans);
return 0;
}