The magic shop in Mars is offering some magic coupons. Each coupon hasan integer N printed on it, meaning that when you use this coupon with aproduct, you may get N times the value of that product back! What ismore, the shop also offers some bonus product for free. However, if youapply a coupon with a positive N to this bonus product, you will have topay 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 productvalues {7 6 -2 -3} (in Mars dollars M\$) where a negative valuecorresponds 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 2to get M\$12 back; and coupon 4 to product 4 to get M\$3 back. On theother hand, if you apply coupon 3 to product 4, you will have to payM\$12 to the shop.
Each coupon and each product may be selected at most once. Your task isto get as much money back as possible.
Input Specification:
Each input file contains one test case. For each case, the first linecontains the number of coupons NC, followed by a line with NC couponintegers. 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^.
Output Specification:
For each test case, simply print in a line the maximum amount of moneyyou can get back.
Sample Input:
4
1 2 4 -1
4
7 6 -2 -3
Sample Output:
43
要求:输入各个coupon的值和各个Product的值,得到两两乘积的正数和的最大值。
思路:想到负数与负数相互搭配,正数和正数相互搭配,
1、得到输入的值,存放在数组中co[],pro[],根据从大到小排序
2、每个数组分别在头尾设置各一个int类型,指向首尾两个位置,c1,c2,p1,p2。
3、首和首相乘,尾和尾相乘, 取大的整数,加到sum中,直到只有负数或者某个数组的值遍历结束。
代码如下:
#include <iostream> #include <cstdio> #include <algorithm> #define Maxsize 100010 using namespace std; int main() { int nc,np; int i; long left,right; unsigned long sum=0; int co[Maxsize]={0},pro[Maxsize]={0}; int c1,c2,p1,p2; scanf("%d",&nc); for(i=0;i<nc;i++) { scanf("%d",&co[i]); } scanf("%d",&np); for(i=0;i<np;i++) { scanf("%d",&pro[i]); } sort(co,co+nc); //排序 sort(pro,pro+np); c1=p1=0; c2=nc-1; p2=np-1; while(c1<=c2 && p2>=p1) //当存在某个数组遍历结束,跳出循环 { left=co[c1]*pro[p1]; right= co[c2]*pro[p2]; if(left> 0 && left >=right ) //假如左边得整数大 sum+= c1,p1右移 { sum+=left; c1++; p1++; continue; } if(right >0 && right>=left) //假如右边的正数大,sum+=, c1,p1左移 { sum+=right; c2--; p2--; continue; //else 或者continue用一个,否则,left和right没有更新就比较。 } if(right<=0 && left <=0) break; } printf("%ld",sum); return 0; }