1009 Product of Polynomials (25 分)
This time, you are supposed to find A×BA\times BA×B where AAA and BBB are two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
KKK N1N_1N1 aN1a_{N_1}aN1 N2N_2N2 aN2a_{N_2}aN2 ... NKN_KNK aNKa_{N_K}aNK
where KKK is the number of nonzero terms in the polynomial, NiN_iNi and aNia_{N_i}aNi (i=1,2,⋯,Ki=1, 2, \cdots , Ki=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤101\le K \le 101≤K≤10, 0≤NK<⋯<N2<N1≤10000 \le N_K < \cdots < N_2 < N_1 \le 10000≤NK<⋯<N2<N1≤1000.
Output Specification:
For each test case you should output the product of AAA and BBB in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate up to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 3 3.6 2 6.0 1 1.6
给两个多项式,格式为:k(该多项式的项数) 指数 系数
求这两个多项式相乘的结果,输出项数以及各个指数从大到小的非零项。
思路:模拟,数据规模不大,用数组即可(如果数据规模大的话可能要用键值对树存储)。注意有个坑点:结果要输出非零项的项数以及非零项,项数的问题很容易忽略!然后指数它的测试数据为整数(如果为浮点数的话注意考虑精度问题)
Code:
#include <bits/stdc++.h>
using namespace std;
const double esp = 1e-6;
struct Node {
double zhishu;
double xishu;
Node operator * (const Node& A) const {
Node tmp;
tmp.zhishu = zhishu + A.zhishu;
tmp.xishu = xishu * A.xishu;
return tmp;
}
bool operator == (const Node& A) const { //指数相同
if (fabs(zhishu - A.zhishu) <= esp) {
return true;
}
return false;
}
bool operator < (const Node& A) const {
return zhishu > A.zhishu;
}
};
int k1,k2;
vector<Node> A, B, C;
int main() {
Node tmp;
A.clear(); B.clear(); C.clear();
cin >> k1;
for (int i = 0; i < k1; i++) {
cin >> tmp.zhishu >> tmp.xishu;
A.push_back(tmp);
}
cin >> k2;
for (int i = 0; i < k2; i++) {
cin >> tmp.zhishu >> tmp.xishu;
B.push_back(tmp);
}
for (int i = 0; i < k1; i++) {
for (int j = 0; j < k2; j++) {
tmp = A[i] * B[j];
int z = 0;
for (; z < C.size(); z++) {
if (tmp == C[z]) {
break;
}
}
if (z < C.size()) {
C[z].xishu += tmp.xishu;
} else {
C.push_back(tmp);
}
}
}
for (vector<Node>::iterator it = C.begin(); it != C.end(); it++) {
if (fabs(it->xishu) <= esp) {
C.erase(it);
}
}
sort(C.begin(), C.end());
printf("%d", C.size());
for (int i = 0; i < C.size(); i++) {
printf(" %.0lf %.1lf", C[i].zhishu, C[i].xishu);
}
printf("\n");
return 0;
}