#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
// 定义多项式的项
struct Term {
int coefficient;
int exponent;
};
// 读入一个多项式
vector<Term> readPolynomial() {
vector<Term> polynomial;
int index, coefficient, exponent;
while (cin >> index) {
if (index == -1) break;
cin >> coefficient >> exponent;
polynomial.push_back({coefficient, exponent});
}
return polynomial;
}
// 多项式乘法
vector<Term> multiplyPolynomials(const vector<Term>& p1, const vector<Term>& p2) {
vector<Term> result;
for (const auto& term1 : p1) {
for (const auto& term2 : p2) {
int newCoefficient = term1.coefficient * term2.coefficient;
int newExponent = term1.exponent + term2.exponent;
result.push_back({newCoefficient, newExponent});
}
}
// 合并同类项
sort(result.begin(), result.end(), [](const Term& a, const Term& b) {
return a.exponent > b.exponent;
});
vector<Term> simplified;
for (const auto& term : result) {
if (simplified.empty() || simplified.back().exponent != term.exponent) {
simplified.push_back(term);
} else {
simplified.back().coefficient += term.coefficient;
}
}
// 移除系数为0的项
simplified.erase(remove_if(simplified.begin(), simplified.end(), [](const Term& term) {
return term.coefficient == 0;
}), simplified.end());
return simplified;
}
// 按照要求的格式输出多项式
void printPolynomial(const vector<Term>& polynomial) {
bool isFirstTerm = true;
for (const auto& term : polynomial) {
if (!isFirstTerm) cout << " ";
isFirstTerm = false;
if (term.coefficient == 0) continue;
if (term.coefficient == 1 && term.exponent != 0) {
cout << "x^" << term.exponent;
} else if (term.coefficient == -1 && term.exponent != 0) {
cout << "-x^" << term.exponent;
} else if (term.coefficient != 0) {
cout << term.coefficient << "x^" << term.exponent;
} else if (term.exponent == 0) {
cout << term.coefficient;
}
}
}
int main() {
vector<Term> polynomial1 = readPolynomial();
vector<Term> polynomial2 = readPolynomial();
vector<Term> result = multiplyPolynomials(polynomial1, polynomial2);
// 按照要求的格式输出结果
printPolynomial(result);
return 0;
}