0
点赞
收藏
分享

微信扫一扫

PTA甲级 1002 题解

醉东枫 2022-02-23 阅读 63

多项式加法,先输出项数,再按指数递减顺序输出答案。

思路:用一个map映射储存每对指数和系数,分别运算,因为要求指数递减,所以重写了set的排序。

#include<iostream>
#include<vector>
#include<map>
using namespace std;
struct cmp
{
    bool operator()(const int& a, const int& b)
        const {
        return a > b;
    }
};
int main(void)
{
    map<int, double, cmp>ma;
    int n, a;
    double b;
    cin >> n;
    while (n--)
    {
        cin >> a >> b;
        ma[a] += b;
    }
    cin >> n;
    while (n--)
    {
        cin >> a >> b;
        ma[a] += b;
        if(ma[a]==0)//小坑点,删除系数为0的数
            ma.erase(a);
    }
    cout << ma.size();
    for (map<int, double>::iterator it = ma.begin(); it != ma.end(); it++)
        printf(" %d %.1lf", it->first, it->second);
    return 0;
}
举报

相关推荐

0 条评论