【A1037】 Magic Coupon

在这里插入图片描述

Sample Input:

4
1 2 4 -1
4
7 6 -2 -3

Sample Output:

43

代码及思路:

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

int main()
{
    int numCoupon, numProduct, Coupon[100010], Product[100010];
    scanf("%d", &numCoupon);
    for (int i = 0; i < numCoupon; i++)
        scanf("%d", &Coupon[i]);
    scanf("%d", &numProduct);
    for (int i = 0; i < numProduct; i++)
        scanf("%d", &Product[i]);

    //最多可获得的钱与coupon和product有什么关系?
    //1.存在正max的情况:
    //max = 最大正coupon * 最大正product
    //or max = 最小负coupon * 最小负product
    //2.不存在正max,也就是coupon和product是相反的清一色, 当然此时不选,要不还得赔钱:
    //max = 最小正coupon * 最大负product 或 最大负product * 最小正coupon
    sort(Coupon, Coupon + numCoupon);
    sort(Product, Product + numProduct);
    int Cleft = 0, Cright = numCoupon - 1;  //标示剩下没选的coupon
    int Pleft = 0, Pright = numProduct - 1; //标示剩下没选的product
    int gain = 0;
    while (Cleft <= Cright && Pleft <= Pright)
    {
        //存在正max
        if (Coupon[Cleft] * Product[Pleft] >= 0 || Coupon[Cright] * Product[Pright] >= 0)
        {
            //max = 最小负coupon * 最小负product
            if (Coupon[Cleft] * Product[Pleft] > Coupon[Cright] * Product[Pright])
            {
                gain += Coupon[Cleft] * Product[Pleft];
                Cleft++;
                Pleft++;
            }
            //max = 最小负coupon * 最小负product
            else
            {
                gain += Coupon[Cright] * Product[Pright];
                Cright--;
                Pright--;
            }
        }
        //没有正max了,停止循环
        else
            break;
    }
    printf("%d\n", gain);

    return 0;
}
发布了30 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lvmy3/article/details/103930851