PAT A 1009 Product of Polynomials

This time, you are supposed to find A*B where A and B are twopolynomials.

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, andeach line contains the information of a polynomial: K N1 a~N1~ N2 a~N2~... NK a~NK~, where K is the number of nonzero terms in the polynomial,Ni and a~Ni~ (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 extraspace 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

先把多项式输入到p数组中,然后在输入另一个多项式的同时,计算每一项的乘积存到ans数组中。

#include<cstdio>
double p[1010] = {0};
double ans[2010] = {0};    //最大1000+1000=2000
int main() {
    int k1,k2, i,j, e;
    double c;

    scanf("%d", &k1);
    for (i = 0; i < k1; i++) {
        scanf("%d %lf", &e, &c);
        p[e] = c;
    }
    scanf("%d", &k2);
    for (i = 0; i < k2; i++) {
        scanf("%d %lf", &e, &c);
        for (j = 0; j <= 1000; j++) {        //j取到1000,不是k1
            ans[j + e] += p[j] * c;
        }
    }
    int count = 0;
    for (i = 0; i <= 2000; i++) {
        if (ans[i])count++;
    }
    printf("%d", count);
    for (i = 2000; i >= 0; i--) {
        if (ans[i]) printf(" %d %.1f", i, ans[i]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/joah_ge/article/details/80539420