02-線性結構2 一元多項式的乘法與加法運算(20 分)
阿新 • • 發佈:2019-02-16
**題目來源:中國大學MOOC-陳越、何欽銘-資料結構-2018春
作者: DS課程組
單位: 浙江大學**
問題描述:
設計函式分別求兩個一元多項式的乘積與和。
輸入格式:
輸入分2行,每行分別先給出多項式非零項的個數,再以指數遞降方式輸入一個多項式非零項係數和指數(絕對值均為不超過1000的整數)。數字間以空格分隔。
輸出格式:
輸出分2行,分別以指數遞降方式輸出乘積多項式以及和多項式非零項的係數和指數。數字間以空格分隔,但結尾不能有多餘空格。零多項式應輸出0 0。
輸入樣例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
輸出樣例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
解答:這道題我寫的時候思路很奇怪==,請勿模仿,用兩個map分別存兩個多項式{指數:係數}的對應資訊,又用3個set,其中兩個set分別存兩個多項式的指數資訊,用於之後從map中取係數進行運算,另一個set用於結果生成(因為set自動排好序了)。還是推薦採用開大小為1001陣列進行實現,更為直接,我會把陣列實現的程式碼再貼上來。
#include <iostream>
#include <map>
#include <set>
using namespace std;
map<int,int> ExpAndNumA,ExpAndNumB,result;
set <int> ExpA,ExpB,resultSet;
void input(map<int,int> &SomeoneMap,set<int> &SomeoneSet,int N)
{
for(int i=0; i<N; i++)
{
int num,exp;
cin>>num>>exp;
SomeoneMap[exp]=num;
SomeoneSet.insert(exp);
}
}
void add()
{
for(auto it=ExpA.begin(); it!=ExpA.end(); it++)
{
resultSet.insert(*it);
result[*it]=ExpAndNumA[*it];
}
for(auto it=ExpB.begin(); it!=ExpB.end(); it++)
{
if(result.count(*it)==0)
{
resultSet.insert(*it);
result[*it]=ExpAndNumB[*it];
}
else
result[*it]+=ExpAndNumB[*it];
}
}
void multi()
{
for(auto it=ExpA.begin(); it!=ExpA.end(); it++)
{
for(auto it2=ExpB.begin(); it2!=ExpB.end(); it2++)
{
int newExp=*it+*it2;
int newNum=ExpAndNumA[*it]*ExpAndNumB[*it2];
if(result.count(newExp)==0)
{
resultSet.insert(newExp);
result[newExp]=newNum;
}
else
result[newExp]+=newNum;
}
}
}
void output()
{
bool flag=0;
for(auto rit=resultSet.rbegin(); rit!=resultSet.rend(); rit++)
{
if(result[*rit]!=0)
{
flag=1;
if(rit==resultSet.rbegin())
{
cout<<result[*rit]<<" "<<*rit;
}
else
{
cout<<" "<<result[*rit]<<" "<<*rit;
}
}
}
if(!flag)
cout<<"0 0";
}
int main()
{
int N1,N2;
cin>>N1;
input(ExpAndNumA,ExpA,N1);
cin>>N2;
input(ExpAndNumB,ExpB,N2);
result.clear();
resultSet.clear();
multi();
output();
cout<<endl;
result.clear();
resultSet.clear();
add();
output();
return 0;
}