PAT-1009 Product of Polynomials

1009 Product of Polynomials (25 分)

This time, you are supposed to find A×B where A and B are two polynomials.ios

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

Sample Output:

3 3 3.6 2 6.0 1 1.6spa

算法說明:

求多項式乘積AxB,採用數組存儲(非必須),下標表示指數,對應的值表示係數。本想着,記錄兩個多項式可填充的最大下標以減小循環,提升速度,不知爲什麼得不全分,等有時間在調試吧。下面給出多項式乘積的例子:\(f(x),g(x)\)中兩係數下標之和爲\(k\),對應項乘積的和爲\(x^k\)的係數。
\[f(x)=2.4x+3.2\]
\[g(x)=1.5x^2+0.5x\]
\[f(x)·g(x)=3.6x^3+(4.8+1.2)x^2+1.6x\]調試

// 1009 Product of Polynomials.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
#define Max 1000

int main(int argc, char* argv[])
{
    int K,count=0;
    int i,j,e;
    double c;
    double A[Max+1]={0.0};
    double B[Max+1]={0.0};
    double C[2*Max+1]={0.0};
     
    cin >>K;
    for(i=0;i<K;i++){
        cin >>e>>c;
        A[e]=c;
    }
    cin >>K;
    for(i=0;i<K;i++){
        cin >>e>>c;
        B[e]=c;
    }
    for(i=0;i<=Max;i++){
        for(j=0;j<=Max;j++){
            C[i+j]+=A[i]*B[j];
        }
    }
    for(i=0;i<=2*Max;i++){
        if(C[i]!=0.0){
            count++;
        }
    }
    cout << count;
    for(i=2*Max;i>=0;i--){
        if(C[i]!=0.0){
            cout <<" " << i
            << setiosflags(ios::fixed) 
            << setprecision(1) 
            << " " << C[i];
        }
    }
    return 0;
}

2020考研打卡第十一天,今天給zyy炒了回鍋肉,哈哈就是肥了點,油多了點,再接再礪。

天行健,君子以自強不息;地勢坤,君子以厚德載物
相關文章
相關標籤/搜索