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.
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≤105, and it is guaranteed that all the numbers will not exceed 230.
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:分别统计正负数
#include <cstdio>
#include <algorithm>
using namespace std;
int cou1[100020],cou2[100020];
int val1[100020],val2[100020];
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
int nc,np;
while(scanf("%d",&nc)!=EOF)
{
int tmp,c1=0,c2=0,v1=0,v2=0;
for(int i=0;i<nc;++i)
{
scanf("%d",&tmp);
if(tmp>0)
cou1[c1++]=tmp; //正数
else
cou2[c2++]=tmp; //负数
}
scanf("%d",&np);
for(int i=0;i<np;++i)
{
scanf("%d",&tmp);
if(tmp>0)
val1[v1++]=tmp;
else
val2[v2++]=tmp;
}
sort(cou1,cou1+c1,cmp); //正数从大到小排序
sort(cou2,cou2+c2);//负数从小到大
sort(val1,val1+v1,cmp);
sort(val2,val2+v2);
int ans=0;
for(int i=0;i<c1&&i<v1;++i) //统计正数的积
{
ans+=cou1[i]*val1[i];
}
for(int i=0;i<c2&&i<v2;++i) //统计负数的积
{
ans+=cou2[i]*val2[i];
}
printf("%d\n",ans);
}
return 0;
}
参考代码2:
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int Nc[100010];
int Np[100010];
int main()
{
int nc,np;
while(scanf("%d",&nc)!=EOF)
{
for(int i=0;i<nc;++i)
scanf("%d",&Nc[i]);
scanf("%d",&np);
for(int i=0;i<np;++i)
scanf("%d",&Np[i]);
sort (Nc,Nc+nc);
sort (Np,Np+np);
int i=0,j,ans=0;
while(i<nc&&i<np &&Nc[i]<0&&Np[i]<0) //先从前到后统计负数的积
{
ans+=Nc[i]*Np[i];
++i;
}
i=nc-1;
j=np-1;
while(i>=0&&j>=0&&Nc[i]>0&&Np[j]>0) //从后往前统计正数
{
ans+=Nc[i]*Np[j];
--i;
--j;
}
printf("%d\n",ans);
}
return 0;
}