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

Posted by-sknight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[PTA] PAT(A) 1009 Product of Polynomials (25 分)相关的知识,希望对你有一定的参考价值。

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 分)的主要内容,如果未能解决你的问题,请参考以下文章

PAT甲级——A1009 Product of Polynomials

PAT A1009 Product of Polynomials (25 分)

PAT Advanced 1009 Product of Polynomials (25分)

PTA 甲 1009 Product of Polynomials

PAT1009:Product of Polynomials

PAT-A 1009. Product of Polynomials