PAT A1037 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.

Input Specification:

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 <= 10^5^, and it is guaranteed that all the numbers will not exceed 2^30^.

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

解题思路

  1. 两堆数字,有正负,各取一个,乘积为正,则得到乘积数目的钱;乘积为负,则需要付这么多钱
  2. 每个数字只能选一次,0不使用
  3. 目的:赢最多的钱
  4. 两个序列中最大的正数与最大的正数乘,最小的负数与最小的负数乘
  5. 如果只有一个数列有负数,就不适用负数;正数也是如此
  6. 所有数不超过2^30 int, 但是乘积可能超过

    代码平铺直叙,其实也没啥看头

AC代码

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn = 100010; // 数列不超过10^5个数
int nc[maxn], np[maxn];

int main() {
    int a, b;
    scanf("%d", &a);
    for (int i = 0; i < a; i++) {
        scanf("%d", &nc[i]);
    }
    scanf("%d", &b);
    for (int i = 0; i < b; i++) {
        scanf("%d", &np[i]);
    }

    double money = 0;
    int l1, l2, h1, h2;
    l1 = l2 = h1 = h2 = 0;
    sort(nc, nc + a);
    sort(np, np + b);
    while (nc[l1] < 0) l1++;        // 0~l1-1为负数,h1~a-1为正数
    if (nc[l1] == 0) h1 = l1 + 1;   //略过0 
    else h1 = l1;
    while (np[l2] < 0) l2++;        // 0~l2-1为负数,h2~b-1为正数
    if (np[l2] == 0) h2 = l2 + 1;   //略过0
    else h2 = l2;

    int minp = min(l1, l2);         // 负数循环加的次数
    int i = 0, j = 0;
    while(i < l1 && j < l2)
        money += nc[i++] * np[j++];

    i = h1, j = h2;
    a--; b--;
    while(a >= i && b >= j)
        money += nc[a--] * np[b--];

    printf("%.0f", money);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/fried123123/article/details/81517963