题意:两个序列,去相同数量的数,分别相乘求其和的最大值。
思路:分成正数和负数两个部分,每次取绝对值最大的相乘。
代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
using namespace std;
vector<int> v1, v2, v3, v4;
int x, n;
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
if (x > 0) v1.push_back(x);
else v2.push_back(-x);
}
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
if (x > 0) v3.push_back(x);
else v4.push_back(-x);
}
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
sort(v3.begin(), v3.end());
sort(v4.begin(), v4.end());
int ans = 0, p1, p2;
p1 = v1.size()-1; p2 = v3.size()-1;
while (p1 >= 0 && p2 >= 0) {
ans += v1[p1] * v3[p2];
p1--; p2--;
}
p1 = v2.size()-1; p2 = v4.size()-1;
while (p1 >= 0 && p2 >= 0) {
ans += v2[p1] * v4[p2];
p1--; p2--;
}
printf("%d\n", ans);
return 0;
}