码迷,mamicode.com
首页 > 其他好文 > 详细

[PTA] PAT(A) 1009 Product of Polynomials (25 分)

时间:2019-09-03 09:19:07      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:out   put   ima   space   toc   input   cout   turn   NPU   

Problem

portal:1009 Product of Polynomials

Description

Input

Output

Sample

Sample Input

Sample Output

Solution

Analysis

Code

#include <bits/stdc++.h>
using namespace std;

struct item {
    double coefficient;
    int exponent;

    item operator*(item it) {
        item it_result;
        it_result.coefficient = coefficient * it.coefficient;
        it_result.exponent = exponent + it.exponent;
        return it_result;
    }
};

struct polynomials {
    vector<item> items;
    polynomials operator*(polynomials &po) {
        polynomials po_result;
        item it_result;
        int pos = 0;
        for (int i = 0; i < items.size(); i++) {
            pos = 0;
            for (int j = 0; j < po.items.size(); j++) {
                it_result = items[i] * po.items[j];
                while (pos < po_result.items.size() && po_result.items[pos].exponent > it_result.exponent)
                    pos++;
                if (pos >= po_result.items.size()) {
                    po_result.items.push_back(it_result);
                } else if (po_result.items[pos].exponent == it_result.exponent) {
                    po_result.items[pos].coefficient += it_result.coefficient;
                } else {
                    po_result.items.insert(po_result.items.begin() + pos, it_result);
                }
            }
        }
        for (int i = 0; i < po_result.items.size(); i++) {
            if (po_result.items[i].coefficient == 0) {
                po_result.items.erase(po_result.items.begin() + i);
                i--;
            }
        }
        return po_result;
    }
};

istream& operator>>(istream &is, polynomials &po) {
    po.items.clear();
    int n;
    item it;
    is >> n;
    for (int i = 0; i < n; i++) {
        is >> it.exponent >> it.coefficient;
        po.items.push_back(it);
    }
    return is;
}

ostream& operator<<(ostream &os, polynomials &po) {
    os << po.items.size();
    for (int i = 0; i < po.items.size(); i++) {
        os << " " << po.items[i].exponent;
        os << fixed << setprecision(1) << " " << po.items[i].coefficient;
    }
    return os;
}

int main(void) {
    polynomials po1, po2, po3;
    cin >> po1 >> po2;
    po3 = po1 * po2;
    cout << po3 << endl;
}

Result

技术图片

[PTA] PAT(A) 1009 Product of Polynomials (25 分)

标签:out   put   ima   space   toc   input   cout   turn   NPU   

原文地址:https://www.cnblogs.com/by-sknight/p/11450802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!