C++解PAT A1037 M(双指针+贪心)
作者:互联网
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.
火星的魔法商店提拱了一些魔法礼券,每个礼券有一个N因在上面上,意思是当你用这个礼券时,你可以有N次机会获得产品,更有甚至,商店也提供了一些免费礼券,然后如果你支付N礼券你获得礼券产品,你将不得不支付N次礼券产品的价值,但神奇的是,一些礼券有负数N。举个例子。给你礼券集合1,2,4,01和一个产品机会,7,6,-2,-3在火星前,其中负数对应于奖励产品,你可以使用优惠券3()
Input Specification:
Each input file contains one test case. For each case, the first line contains the number of coupons N C , followed by a line with N C coupon integers. Then the next line contains the number of products N P , followed by a line with N P product values. Here 1≤N C ,N P ≤10 , and it is guaranteed that all the numbers will not exceed 2 30
输入规格:每个输入文件包含一个测试案例,每个测试案例,第一行包含礼券 .Nc的书来那个,然后接下来一行包含N个礼券的集合,随着一行给出产品的书来那个,给出产品的集合,礼券和产品不会超过10^5,保证所有的数字不会超出 2 30 2^{30} 230
Output Specification:
For each test case, simply print in a line the maximum amount of money you can get back.
输出规格,每个测试文件,仅仅打印一钱最多大获得。
思路核心
首先肯定是全局贪心,贪心完直接双指针就行了,也没啥大问题。主要是思路先理清楚,先排序处理完一部分数字,然后双指针,一起从尾巴进行配对!
核心思路
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn = 1000010;
int coupon[maxn],product[maxn];
int main()
{
//freopen("C:\\Users\\Administrator\\Desktop\\test\\input.txt","r",stdin);
int n,m;
scanf("%d",&n);
for(int i =0;i<n;i++){
scanf("%d",&coupon[i]);
}
scanf("%d",&m);
for(int i =0;i<m;i++){
scanf("%d",&product[i]);
}
sort(coupon,coupon+n);//从小到大排序
sort(product,product+m);//从小到大排序
int i = 0,j,ans = 0;//ans存放乘积之和
while(i<n && i<m && coupon[i]<0 && product[i]<0){
ans += coupon[i] * product[i];//当前位置均小于0时,累加乘积
i++;
}
i=n-1;
j = m-1;
while(i>=0 && j>=0 && coupon[i]>0 && product[j]>0){
ans+=coupon[i] * product[j];
i--;j--;
}
printf("%d\n",ans);
}
标签:product,PAT,get,coupon,back,礼券,A1037,int,C++ 来源: https://blog.csdn.net/m0_37149062/article/details/122616785