原题:
The magic shop in Mars is offering some magic coupons. Each coupon has an integer N NN printed on it, meaning that when you use this coupon with a product, you may get N NN 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 NN to this bonus product, you will have to pay the shop N NN times the value of the bonus product… but hey, magically, they have some coupons with negative N NN's!
For example, given a set of coupons { 1 2 4 − 1 −1−1 }, and a set of product values { 7 6 − 2 − 3 −2 −3−2−3 } (in Mars dollars M$) where a negative value corresponds to a bonus product. You can apply coupon 3 (with N NN 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 Nocoupon 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。
Input 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
1
2
3
4
Sample Output:
43
解题思路:
本题考查的是两组数列中,所有同号的两个数字乘积相加的最大值。让两个数组进行降序排列,分别定义两个指针指向各自数组的最大值。进入循环,如果两个数字都是正号,则相乘并相加到最终结果。然后指针同时右移。若其中有一个数字为负,则两个指针同时指向尾部。若尾部数字为负,则相乘并相加到最终结果。两个指针同时左移。若其中有一个数字为负,则停止循环。
#include <stdio.h>
#include <stdlib.h>
#define maxn 100000
int cou[maxn];
int pri[maxn];
//bubbleSort
void swap (int *a,int *b){
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void bubbleSort(int* arr, int n){
for(int i=n-1;i>0;i--){
for(int j = 0;j<i;j++){
if(arr[j+1]>arr[j]){
swap(&(arr[j+1]),&(arr[j]));
}
}
}
}
int main (){
int nc,np;
scanf("%d",&nc);
for(int i=0;i<nc;i++){
scanf("%d",cou+i);
}
scanf("%d",&np);
for(int i=0;i<np;i++){
scanf("%d",pri+i);
}
//把两个数组改成降序排列
bubbleSort(cou,nc);
bubbleSort(pri,np);
//用两个指针,每次找到绝对值最大数
int sum = 0;
int i=0;
int j=0;
int midI,midJ;
while(i<nc&&j<np){
if(cou[i]>0&&pri[j]>0){
sum+=cou[i]*pri[j];
i++;
j++;
}else if(cou[i]<=0 || pri[j]<=0){
midI=i;
midJ =j;
break;
}
}
i=nc-1;
j=np-1;
while(i>midI&&j>midJ){
if(cou[i]<0&&pri[j]<0){
sum+=cou[i]*pri[j];
i--;
j--;
}else if(cou[i]<=0 || pri[j]<=0){
break;
}
}
printf("%d",sum);
return 0;
}