PAT 1009 Product of Polynomials (25分)

题目链接:点击这里

题意:计算 A 乘以 B,其中 A 和 B 是两个多项式。

思路:多项式相乘,就是用 A A A 的每一项去乘以 B B B 的每一项,系数相乘,指数相加。

如下表所示,可以用一维数组存储多项式。

样例 2 1 2.4 0 3.2 可以表示成 2.4 x + 3.2 2.4x+3.2 2.4x+3.2,其在数组中的存储如下:

样例 2 2 1.5 1 0.5 可以表示成 1.5 x 2 + 0.5 x 1.5x^2+0.5x 1.5x2+0.5x,其在数组中的存储如下:

两者相乘的结果为 3.6 x 3 + 6.0 x 2 + 1.6 x 3.6x^3+6.0x^2 +1.6x 3.6x3+6.0x2+1.6x,其在数组中的存储如下:

在这里插入图片描述

AC代码:

#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;
}

微信公众号《算法竞赛求职》,致力于详细讲解竞赛和求职所涉及到的算法原理和模板。欢迎关注,一起交流进步!

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/108994560