PAT (Advanced Level) Practice 1009 Product of Polynomials (25 分) 凌宸1642
题目描述:
This time, you are supposed to find A×B where A and B are two polynomials.
译:这一次,你需要找出 A x B ,其中 A 和 B 是两个多项式。
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.
译:每个输入文件包含一个测试用例,每个用例包含两行,每一行包含一个多项式的信息:
K N1 aN1 N2 aN2… NK aNK
其中 K 是多项式非零项的个数, Ni 和 aNi (i=1,2,⋯,K) 分别是每一项的指数和系数。给定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.
译:对于每个测试用例,在一行中以输入形式输出A 和 B 的乘积,注意,行末必须没有额外的空格。请精确到小数点后一位。
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
The Idea:
分别利用两个按关键字的降序排列的map,然后模拟多项式的乘积,注意在得到乘积后,要去除乘积多项式中的零项。
The Codes:
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1010 ;
map<int, double , greater<int> > mp1 , mp2 , ans ;
map<int, double , greater<int> >::iterator it , it2 ;
int k , e , e1 , e2 , en ;
double coe , coe1 , coe2 , coen;
void input(int k , map<int , double , greater<int> > &mp){
for(int i = 0 ; i < k ; i ++) {
cin >> e >> coe ;
mp[e] = coe ;
}
}
int main(){
cin >> k ;
input(k ,mp1) ;
cin >> k ;
input(k ,mp2) ;
for(it = mp1.begin() ; it != mp1.end() ; it ++){
e1 = it ->first ;
coe1 = it -> second ;
for(it2 = mp2.begin() ; it2 != mp2.end() ; it2 ++){
e2 = it2 ->first ;
coe2 = it2 -> second ;
en = e1 + e2 ;
coen = coe1 * coe2 ;
ans[en] += coen ;
}
}
for(it = ans.begin() ; it != ans.end() ; it ++) // 排除零项
if(it -> second == 0) ans.erase(it) ;
cout << ans.size() ;
for(it = ans.begin() ; it != ans.end() ; it ++)
printf(" %d %.1f" , it ->first , it -> second) ;
cout << endl ;
return 0 ;
}