PAT 1009 Product of Polynomials (25分)

Topic link: click here

Question: Calculate A multiplied by B, where A and B are two polynomials.

Idea: Multiply polynomials, use AAA each multiplied toBBFor each item of B , the coefficients are multiplied and the exponents are added.

As shown in the following table, one-dimensional arrays can be used to store polynomials.

Example 2 1 2.4 0 3.2 can be expressed as 2.4 x + 3.2 2.4 x + 3.22 . 4 x+. 3 . 2 , which is stored in the array as follows:

Example 2 2 1.5 1 0.5 can be expressed as 1.5 x 2 + 0.5 x 1.5x^2+0.5x1.5x2+0 . . 5 X , which is stored in the array as follows:

The result of multiplying the two is 3.6 x 3 + 6.0 x 2 + 1.6 x 3.6x^3+6.0x^2 +1.6x3.6x3+6.0x2+. 1 . . 6 X , which is stored in the array as follows:

Insert picture description here

AC code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

double a[1010], b[1010], c[2010];

int main()
{
    
    
    int n, exp, aexp = -1, bexp = -1;
    double coe;
    
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
    {
    
    
        scanf("%d%lf", &exp, &coe);
        aexp = max(aexp, exp);
        a[exp] = coe;
    }
    
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
    {
    
    
        scanf("%d%lf", &exp, &coe);
        bexp = max(bexp, exp);
        b[exp] = coe;
    }
    
    for(int i = 0; i <= aexp; i++)
        for(int j = 0; j <= bexp; j++)
            c[i + j] += a[i] * b[j];
    
    int ans = 0;
    for(int i = aexp + bexp; i >= 0; i--)   ans += (c[i] != 0);
    printf("%d", ans);
    
    for(int i = aexp + bexp; i >= 0; i--)
        if(c[i] != 0)
            printf(" %d %.1f", i, c[i]);
    
    return 0;
}

The WeChat public account "Algorithm Competition Job Search" is dedicated to explaining in detail the algorithm principles and templates involved in the competition and job search. Welcome to pay attention and communicate and progress together!

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/108994560