甲級-1009 Product of Polynomials (25 分)

題目:

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 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≤NK<?<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

解題思路:

兩層循環(huán),分別將兩個序列的每個元素的系數(shù)相乘、指數(shù)相加,最后再將具有相同指數(shù)的系數(shù)相加合并即可。
注意在此處只需要將系數(shù)真正為0的元素去除,而不需要將系數(shù)<0.05的元素去除,雖然后者在保留一位小數(shù)的情況下顯示出來為0.0。

代碼:

編譯器:C++(g++)

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main()
{
    int k;
    cin>>k;
    map<int,double> fi;
    for(int i=0;i!=k;++i)
    {
        int t1;
        double t2;
        cin>>t1>>t2;
        fi[t1]=t2;
    }
    cin>>k;
    map<int,double> si;
    for(int i=0;i!=k;++i)
    {
        int t1;
        double t2;
        cin>>t1>>t2;
        si[t1]=t2;
    }
    map<int,double> result;
    for(auto i=fi.begin();i!=fi.end();++i)
    {
        for(auto j=si.begin();j!=si.end();++j)
        {
            result[i->first+j->first]+=i->second*j->second;
        }
    }
    //刪除系數(shù)為0的項
    for(auto i=result.begin();i!=result.end();)
    {
        if(i->second<=1e-15&&i->second>=-1e-15)
            i=result.erase(i);
        else
            ++i;
    }
    cout<<result.size();
    cout.flags(ios::fixed);
    cout.precision(1);
    for(auto i=result.rbegin();i!=result.rend();++i)
    {
        cout<<" "<<i->first<<" "<<i->second;
    }
    cout<<endl;
    return 0;
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容