PAT甲级之路--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

题目翻译 :这次你需要计算的是A*B,A和B是两个多项式。

输入:每一组输入包含一组测试,每个测试包含两行,每行包含格式如下

K N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ ... N​K​​ a​N​K​​​​

K是非零项的数目,Ni和aNi是指数和系数(1≤K≤10, 0≤N​K​​<⋯<N​2​​<N​1​​≤1000)

输出:一行,A*B所得的多项式

思路分析:之前做过了A+B的问题,参考以前的方法,利用double数组存储,i为下标,数组值为系数,首先输入一个多项式存储到A[i]中,接下来边输入B[i]边计算,每输入一项检测将其与A[i]的非零项指数相加系数相乘,最后遍历整个数组得到非零项个数,然后依次输出。需要注意的是每一个多项式最高指数为1000,所以A*B的最大指数为2000

参考代码:

#include<iostream>
#include <cmath>
#include <iomanip>
using namespace std;
#define MaxN 2001
int main(){
    int N1,N2,Count=0;
    double A[MaxN],B[MaxN];
     for(int i=0;i<MaxN;i++){
        A[i] = 0;
        B[i] = 0;
    }
    cin>>N1;
    for(int i =0;i < N1;i++){
            int exp1;
            double coef1;
        cin>>exp1>>coef1;
        A[exp1]=coef1;
    }
    cin>>N2;
    for(int j =0;j < N2;j++){
            int exp2;
            double coef2;
        cin>>exp2>>coef2;

        for(int i=0;i<MaxN;i++)
        if(A[i]!=0&&exp2+i<MaxN){
             B[exp2+i]+=A[i]*coef2;
        }

    }

    for(int i=0;i<MaxN;i++){
        if(B[i]!=0)
           Count++;
    }
    cout<<Count;
    for(int i=MaxN-1;i>=0;i--){
        if(B[i]!=0)
           cout<<" "<<i<<" "<<fixed<<setprecision(1)<<B[i];
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值