题目大意:
求两个多项式的乘积,输入输出格式与[PAT-A 1002]A+B for Polynomials一致。
思路:
1.同PAT-A 1002,先输入保存多项式a,对第二个多项式b输入过程中每次输入与a中的每项系数相乘,指数相加,保存在double ans[maxn*2]中,输出过程也相同。
2.在计算乘积时要与a中的每一项相乘,即循环次数为maxn次,不是m的个数。
for (int i = 0; i < n; i++) {
(void)scanf("%d %lf", &exp, &cof);
for (int j = 0; j < 1010; j++) {
ans[exp + j] += (cof * a[j]);
}
}
AC代码:
//PAT_A 1009
#include<cstdio>
using namespace std;
int main() {
int m, n, exp, count = 0;
double cof, a[1010] = { 0 }, ans[2020] = { 0 };//ans存放答案
(void)scanf("%d", &m);//第一个多项式中非0项个数
for (int i = 0; i < m; i++) {
(void)scanf("%d %lf", &exp, &cof);
a[exp] += cof;
}
(void)scanf("%d", &n);//第二个多项式中的非0项个数
for (int i = 0; i < n; i++) {
(void)scanf("%d %lf", &exp, &cof);
for (int j = 0; j < 1010; j++) {
ans[exp + j] += (cof * a[j]);
}
}
for (int i = 0; i < 2020; i++) {
if (ans[i] != 0.0)count++;
}
printf("%d", count);
for (int i = 2000; i >= 0; i--) {
if (ans[i] != 0.0)printf(" %d %.1f", i, ans[i]);
}
return 0;
}