PAT_A 1009 Product of Polynomials

PAT_A 1009 Product of Polynomials

分析

本题是多项式相乘,需要注意的是随着运算的进行,会出现新的指数项,因此不同于A1002的多项式相加,这里采用了map的做法;同时尝试了使用auto遍历map的方法。

题目的描述

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

AC的代码

#include<bits/stdc++.h>

using namespace std;

int main(){
    int K=0,c=0;
    long long m=-1;
    //array<double 1001> A={0},B={0};
    map<long long ,double> A,B,C;
    
    cin>>K;
    while(K--){
        long long  t1;
        double t2;
        cin>>t1>>t2;
        if(!(A.count(t1))){
            A[t1]=t2;
        }
        else{
            A[t1]+=t2;
        }
    }
    cin>>K;
    while(K--){
        long long  t1;
        double t2;
        cin>>t1>>t2;
        if(!(B.count(t1))){
            B[t1]=t2;
        }
        else{
            B[t1]+=t2;
        }
    }
    for(auto i:A){
        for(auto j:B){
            long long  t1 = i.first+j.first;
            double t2 = i.second*j.second;
            if(!(C.count(t1))){
                C[t1]=t2;
            }
            else {
                C[t1]+=t2;
            }
        }
    }
    for(auto i:C){
        if(i.second!=0.0){
            c+=1;
            if(i.first>m)m=i.first;
        }
    }
    cout<<c;
    for(int i=m;i>=0&&m;i--){
        if(C.count(i)&&C[i]!=0.0){
            printf(" %d %.1f",i,C[i]);
        }
    }
    cout<<endl;
    return 0;
}
posted @ 2022-01-24 22:36  ghosteq  阅读(20)  评论(0编辑  收藏  举报