我的方法
#include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
const int maxn = 100010;
bool cmp(int m, int n){
return m > n ;
}
int main(int argc, char** argv) {
int a[maxn], b[maxn];
int c ,p;
long long int ans = 0;
cin >> c;
for(int i = 0; i < c; i++){
cin >> a[i];
}
cin >> p;
for(int i = 0; i < p; i++){
cin >> b[i];
}
sort(a, a+c, cmp);
sort(b, b+c, cmp);
int minn = c < p ? c : p;
int q = minn;
int i = 0, j = 0;
while(minn--){
if(a[i] > 0 && b[j] > 0){
ans += (a[i]*b[j]);
i++;
j++;
} else if(a[i] > 0 && b[j] < 0){
i++;
} else if(a[i] < 0 && b[j] > 0){
j++;
} else if(a[i] < 0 && b[j] < 0){
break;
}
}
//cout << "?aaa" << a[c-1] << " " << b[p-1];
while(q--){
if(a[c-1] < 0 && b[p-1] < 0){
ans += (a[c-1] * b[p-1]);
c--; p--;
} else {
break;
}
}
cout << ans;
return 0;
}
简便方法
#include <bits/stdc++.h>
using namespace std;
/*----------------------方法二 -----------------------*/
const int maxn = 100010;
int coupon[maxn], product[maxn];
int main(){
int n, m;
cin >> n;
for(int i = 0; i < n; i++){
cin >> coupon[i];
}
cin >> m;
for(int i = 0; i < m; i++){
cin >> product[i];
}
sort(coupon, coupon+n);
sort(product, product+m);
int i = 0, j, ans = 0;
while(i < n && i < m && coupon[i] < 0 && product[i] < 0){
ans += coupon[i] * product[i];
i++;
}
i = n-1;
j = m-1;
while(i >= 0 && j >= 0 && coupon[i] > 0 && product[j] > 0){
ans += coupon[i] * product[j];
i--; j--;
}
cout << ans;
return 0;
}