PAT A1037 Magic Coupon魔术券【贪心】

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

比如说,给你一系列券{1 2 4 -1},一系列产品价格{7 6 -2 -3}(单位是火星美元M$),负数价格对应的是福利产品。你可以对商品1(价格是7M$)使用券3(N为4),得到28M$。对商品2使用券2会得到12M$;对商品4使用券4会得到3M$。另一方面,如果你对商品4使用券3,你需要支付12M$。

每一个券和每一个商品只能选择一次,你的任务是尽可能得到更多的钱

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

每一个测试样例第一行包含了券的数量NC,之后一行是NC个券的整数。

下一行包含了商品数NP,之后一行是NP个商品的价格

1≤NC,NP≤10^5。所有的数都不会超过2^30

Output Specification:

For each test case, simply print in a line the maximum amount of money you can get back.

输出你能得到的最大钱数。

思路:对于每一个集合,将正数和负数分开考虑。然后对每个集合的正数按照从大到小的顺序进行排序;对于负数,按从小到大的顺序进行排序。排序完毕后,对两个集合进行相同位置上的正数和正数相乘、负数和负数相乘。累加所得乘积。

对于正数,大*大

对于负数,小*小

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=100010;
int coupon[maxn],product[maxn];
int main(){
	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;
	while(i<n&&i<m&&coupon[i]<0&&product[i]<0){
		ans+=coupon[i]*product[i];
		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);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38179583/article/details/86615188