a1009 product of polynomials

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 N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ … N​K​​ a​N​K​​​​

where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10, 0≤N​K​​<⋯<N​2​​<N​1​​≤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 <bits/stdc++.h>

const int max_n = 2001;
double arr[max_n] = {0}; 
struct Poly
{
    int exp;      //指数
    double coeff; //系数
} poly[1001];     //第一个多项式

int main()
{
    int K1, K2;             //第一,二个多项式非零项的项数
    int exponents;         //指数
    double coefficients; //系数
    //读入第一个多项式
    scanf("%d", &K1);
    for (int i = 0; i < K1; i++)
    {
        scanf("%d%lf", &poly[i].exp, &poly[i].coeff);
    }
    //读入第二个多项式
    scanf("%d", &K2);
    for (int i = 0; i < K2; i++)
    {
        scanf("%d%lf", &exponents, &coefficients);
        //与第一个多项式相乘
        //系数相乘,指数相加
        for (int j = 0; j < K1; j++)
        {
            arr[exponents + poly[j].exp] += (coefficients * poly[j].coeff);
        }
    }

    //计算非零系数项的个数
    int count = 0;
    for (int i = 0; i < max_n; i++)
    {
        if (arr[i] != 0)
            count++;
    }

    //输出多项式
    printf("%d", count);
    for (int i = max_n; i >= 0; i--)
    {
        if (arr[i] != 0)
            printf(" %d %.1lf", i, arr[i]);
    }

    return 0;
}