#include <iostream>
#include <list>

struct Term {
    int coefficient; // 系数
    int exponent;    // 指数

    Term(int coef, int exp) : coefficient(coef), exponent(exp) {}
};

class Polynomial {
public:
    std::list<Term> terms; // 存储多项式项的列表

    // 构造函数
    Polynomial() {}

    // 从初始化列表构造多项式
    Polynomial(std::initializer_list<Term> init) : terms(init) {}

    // 多项式加法
    Polynomial operator+(const Polynomial& other) {
        Polynomial result;

        auto it1 = terms.begin();
        auto it2 = other.terms.begin();

        while (it1 != terms.end() && it2 != other.terms.end()) {
            if (it1->exponent == it2->exponent) {
                // 指数相同,合并系数
                result.terms.emplace_back(it1->coefficient + it2->coefficient, it1->exponent);
                ++it1;
                ++it2;
            }
            else if (it1->exponent > it2->exponent) {
                // 当前多项式的指数较大
                result.terms.emplace_back(it1->coefficient, it1->exponent);
                ++it1;
            }
            else {
                // 其他多项式的指数较大
                result.terms.emplace_back(it2->coefficient, it2->exponent);
                ++it2;
            }
        }

        // 处理剩余的项
        while (it1 != terms.end()) {
            result.terms.emplace_back(it1->coefficient, it1->exponent);
            ++it1;
        }

        while (it2 != other.terms.end()) {
            result.terms.emplace_back(it2->coefficient, it2->exponent);
            ++it2;
        }

        return result;
    }

    // 打印多项式
    void print() const {
        for (auto it = terms.begin(); it != terms.end(); ++it) {
            if (it != terms.begin() && it->coefficient > 0) {
                std::cout << " + "; // 正系数前加 +
            }
            std::cout << it->coefficient << "x^" << it->exponent;
        }
        std::cout << std::endl;
    }
};

int main() {
    // 初始化多项式
    Polynomial p1 = { {3, 2}, {4, 1}, {5, 0} }; // 3x^2 + 4x + 5
    Polynomial p2 = { {2, 1}, {1, 0} };         // 2x + 1

    // 打印多项式
    std::cout << "Polynomial 1: ";
    p1.print();

    std::cout << "Polynomial 2: ";
    p2.print();

    // 多项式加法
    Polynomial p3 = p1 + p2;

    std::cout << "Sum: ";
    p3.print();

    return 0;
}