题目
题目复杂难懂,翻译过来其实题目的目的就是让最大正数和最大正数相乘,最小负数和最小负数相乘,正负不能相乘,每个数都只能被乘一次。
代码和思路
- 题目说数字的大小是小于2的32次方的,小于int类型,所以就用int定义就好
- 分别读入两个数组后排序
- 然后循环找到每个数组第一个负数出现的位置
- 正数从前往后乘,负数从后往前乘,负数位置就是循环跳出变量
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100010;
int coupon[maxn], product[maxn];
bool cmp(int a, int b) {
return a > b;
}
int main() {
int nc, np;
scanf("%d", &nc);
for (int i = 0; i < nc; i++) {
scanf("%d", &coupon[i]);
}
scanf("%d", &np);
for (int i = 0; i < np; i++) {
scanf("%d", &product[i]);
}
sort(coupon, coupon + nc, cmp);
sort(product, product + np, cmp);
int negflagc = -1, negflagp = -1;
for (int i = 0; i < nc; i++) {
if (coupon[i] < 0) {
negflagc = i;
break;
}
}
if (negflagc == -1) { negflagc = nc; }
for (int i = 0; i < np; i++) {
if (product[i] < 0) {
negflagp = i;
break;
}
}
if (negflagp == -1) { negflagp = np; }
int sum = 0;
int c = 0, p = 0;
while (c < negflagc && p < negflagp) {
sum += coupon[c] * product[p];
c++;
p++;
}
c = nc - 1;
p = np - 1;
while (c >= negflagc && p >= negflagp) {
sum += coupon[c] * product[p];
c--;
p--;
}
printf("%d", sum);
}
题目看懂以后是非常简单的,主要就是题目的描述有点长难。