多项式乘法
就是一个简单的模拟乘法的过程。注意去掉系数为0的,注意下程序的注释,有一个地方要清空!
#include <bits/stdc++.h>
using namespace std;
struct Node {
int exp;
float cof;
};
// node乘以多项式poly,结果存到res中
void mul(const Node& node, const vector<Node>& poly, vector<Node>& res) {
for(auto it = poly.begin(); it != poly.end(); it++) {
Node tmp;
tmp.cof = node.cof * it->cof;
tmp.exp = node.exp + it->exp;
res.push_back(tmp);
}
}
// poly1和poly2相加,结果存到poly3中
void add(const vector<Node>& poly1, const vector<Node>& poly2, vector<Node>& poly3) {
auto it1 = poly1.begin(), it2 = poly2.begin();
while(it1 != poly1.end() && it2 != poly2.end()) {
if(it1->exp == it2->exp) {
Node tmp;
tmp.cof = it1->cof + it2->cof;
tmp.exp = it1->exp;
if(tmp.cof != 0) {
poly3.push_back(tmp);
}
it1++;
it2++;
} else if(it1->exp > it2->exp) {
poly3.push_back(*it1);
it1++;
} else {
poly3.push_back(*it2);
it2++;
}
}
while(it1 != poly1.end()) {
poly3.push_back(*it1);
it1++;
}
while(it2 != poly2.end()) {
poly3.push_back(*it2);
it2++;
}
}
int main() {
vector<Node>poly1, poly2, tmp, res_tmp, res;
Node node;
int n;
cin >> n;
for(int i = 0; i < n; ++i) {
cin >> node.exp >> node.cof;
poly1.push_back(node);
}
cin >> n;
for(int i = 0; i < n; ++i) {
cin >> node.exp >> node.cof;
poly2.push_back(node);
}
for(auto it = poly1.begin(); it != poly1.end(); it++) {
tmp.clear();
res_tmp.clear();
mul(*it, poly2, tmp);
res_tmp = res;
res.clear(); // 一定要清空
add(tmp, res_tmp, res);
}
cout << res.size();
for(auto it = res.begin(); it != res.end(); it++) {
printf(" %d %.1f", it->exp, it->cof);
}
return 0;
}
/*
2 1 2.4 0 3.2
2 2 1.5 1 0.5
*/