[PAT 甲级] 1009 Product of Polynomials (25 分)

版权声明:原创博客,转载请标明出处! https://blog.csdn.net/caipengbenren/article/details/88965229

1009 Product of Polynomials (25 分)

原题链接
This time, you are supposed to find A×B where A and B are two polynomials.

Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
where K is the number of nonzero terms in the polynomial, N

​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that
Output Specification:
For each test case you should output the product of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate up to 1 decimal place.

Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 3 3.6 2 6.0 1 1.6


用pair加vector记录多项式子 或者利用数组记录也可以。


#include<iostream>
#include<vector>
using  namespace std;
vector<pair<int, double> >a;
vector<pair<int, double> >b;
double ans[2001];
int main () {
    int n, exp;
    float coe;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> exp >> coe;
        a.push_back(make_pair(exp, coe));
    }
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> exp >> coe;
        b.push_back(make_pair(exp, coe));
    }
    for (auto it_a = a.begin(); it_a != a.end(); it_a++) {
        for (auto it_b = b.begin(); it_b != b.end(); it_b++) {
            exp = (*it_a).first + (*it_b).first;
            coe = (*it_a).second * (*it_b).second;
            ans[exp] += coe;
        }
    }
    int cnt = 0, max = 0;
    for (int i = 0; i <= 2000 ; i++) {
        if (ans[i] != 0) {
            cnt++;
            max = i;
        }
    }
    cout << cnt;
    for (int i = max; i >= 0; i--) {
        if (ans[i] != 0) {
            printf(" %d %.1f", i, ans[i]);
        }
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/caipengbenren/article/details/88965229