题目


解法1

点击查看代码
#include <iostream>
#include <map>
#include <vector>
#include <iomanip>
using namespace std;

int main() {
    map<int, float, greater<int>> poly; // 按指数降序排列

    // 读取第一个多项式
    int K, exp;
    float cof;
    cin >> K;
    while (K--) {
        cin >> exp >> cof;
        poly[exp] += cof;
    }

    // 读取第二个多项式
    cin >> K;
    while (K--) {
        cin >> exp >> cof;
        poly[exp] += cof;
    }

    // 移除系数为零的项(系数相加后为0)
    int cnt=0;
    for (auto it : poly) {
        if (it.second != 0.0) {
            cnt++;
        }
    }

    // 输出结果
    cout <<cnt;
    for (auto it : poly) {
        if (it.second != 0.0) {
            printf(" %d %.1f",it.first,it.second);
        }
    }

    return 0;
}