PAT甲级1009

多项式乘法

就是一个简单的模拟乘法的过程。注意去掉系数为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
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值