题目
思路
题目大意:给两个数组,每次从两个数组中各取一个数字相乘后相加,使其结果最大;
使用贪心就可以了,由于正数 * 正数,负数 * 负数都是正数,相加都会使结果变大,所以我们不让其进行负数 * 正数的运算;
除此之外,a中最大的正数与b中最大的正数或负数相乘结果值是最大的,即最优解;
先把两个数组都从小到大排序,这样负数肯定都在前面,从前往后都使两个数组对应位都是负数的位相乘,只要有一个出现正数,结束此次迭代;
然后从后往前遍历,使两个数组都是正数的位相乘,只要有一个出现负数,结束此次迭代;
注意使用long long;
代码
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 10;
int main()
{
int a[maxn], b[maxn];
int n, m;
scanf("%d", &n);
for(int i = 0; i < n; i ++) scanf("%d", &a[i]);
scanf("%d", &m);
for(int i = 0; i < m; i ++) scanf("%d", &b[i]);
//从小到大排序,负数在前面
sort(a, a + n);
sort(b, b + m);
long long ans = 0;
int i = 0, j;
//从前往后找,让所有的负数相乘
while(a[i] < 0 && b[i] < 0){
ans += a[i] * b[i];
i ++;
}
i = n- 1, j = m - 1;
//从后往前找,让所有的正数相乘
while(a[i] > 0 && b[j] > 0){
ans += a[i] * b[j];
i --, j --;
}
printf("%lld", ans);
system("pause");
return 0;
}