PAT 甲级练习 1009

1009. Product of Polynomials

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: K N1 aN1 N2 aN2 … NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, …, K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10, 0 <= NK < … < N2 < N1 <=1000.

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

代码如下:

#include <iostream>
#include <vector>
#include <iomanip>

using namespace std;

double abs(double a)
{
    return ((a > 0) ? a : -a);
}

bool db_equal(double a, double b)
{
    return (abs(a - b) < 1E-10 ? true : false);
}

int main()
{
    int exp;
    double coe;

    int k1, k2;
    vector<double> X1(1001, 0.0), X2(1001, 0.0), result(2001, 0.0);

    //read a line
    cin >> k1;
    for(int i=0; i<k1; ++i){
        cin >> exp >> coe;
        X1[exp] = coe;
    }
    //read another line
    cin >> k2;
    for(int i=0; i<k2; ++i){
        cin >> exp >> coe;
        X2[exp] = coe;
    }
    //process
    for(int i=0; i<X1.size(); ++i){
        if(db_equal(X1[i], 0.0)) continue;
        for(int j=0; j<X2.size(); ++j){
            if(db_equal(X2[j], 0.0))   continue;
            //calculate
            result[i+j] += X1[i]*X2[j];
        }
    }
    //count
    int cnt = 0;
    for(int i=0; i<result.size(); ++i){
        if(!db_equal(result[i], 0.0))
            ++cnt;
    }
    cout << cnt;
    //print
    for(int i=result.size() - 1; i>=0; --i){
        if(!db_equal(result[i], 0.0))
            cout << ' ' << i << ' ' << setprecision(1) << fixed << result[i];
    }

    return 0;
}

注意:浮点数由于精度问题不能直接使用 == 比较,应该用 abs(db1 - db2) < eps 比较。

猜你喜欢

转载自blog.csdn.net/linlinlin96/article/details/79477620