PTA甲级-1009 Product of Polynomials c++

该问题要求实现两个多项式的乘法运算,输入是两个多项式,输出是它们的乘积。使用C++的vector存储多项式,通过循环相乘并累加结果。需要注意处理系数为0的情况以及避免额外空格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目内容

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 a**N1 N2 a**N2 … N**K aNK

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

一、题干大意

给出两个多项式,相乘后输出。

输入、输出格式为:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C6S7tkhb-1675569980496)(C:\Users\hhzheng\AppData\Roaming\Typora\typora-user-images\image-20230205115244366.png)]

二、题解要点

  • 用vector实现,下标作指数,内容做系数。循环相乘后保存在result中,每次有相同的指数就往那个数组元素中加进去。
  • 测试点0的内容是要考虑系数为0时不打印、不计数

三、具体实现

/**
*@Author:hhzheng
*@Date:2023/2/5  10:12
*@Filename:PAT甲级1009 Product of Polynomials
*/

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n, zhiShu, count = 0;
    float xiShu;
    vector<double> a(1001, 0.0);
    vector<double> result(2002, 0.0);

    /*先把第一个多项式保存下来*/
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%d %f", &zhiShu, &xiShu);
        a[zhiShu] = xiShu;
    }

    /**当读入第二个多项式的时候进行循环
     * 每读入一个项,就把第一个多项式拿过来相乘
     * 得到的结果放在result中
     * */
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%d %f", &zhiShu, &xiShu);
        for (int j = 0; j < 1001; ++j) {
            if (a[j] != 0) {
                result[j + zhiShu] += a[j] * xiShu;  //两个多项式相乘就是:指数相加、系数相乘
            }
        }
    }

    /**一定要在所有计算都完毕之后再去看一共有多少非零项
     * 不然可能出现某一项一开始的时候是非零的
     * 但是有负的系数把这项的抵消为0了
     * 这样的项不能出现在结果中
     * */
    for (int i = 2002; i >= 0; --i) {
        if (result[i] != 0) {
            count++;
        }
    }
    cout << count;
    for (int i = 2002; i >= 0; --i) {
        if (result[i] != 0.0) {
            printf(" %d %.1lf", i, result[i]);
        }
    }
    cout << endl;
    return 0;
}


总结

测试点0比较坑,一定要注意题干中没说系数不能为负数,那么就要把两项相乘后加到原有数组元素中导致元素的值变为0的情况。

我这给出一个测试用例,你们可以看一下自己的程序是否在这样的测试用例下仍旧能正确输出。

1 0 -1.2
1 0 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值