1009. Product of Polynomials (25)
题目:
This time, you are supposed to find A*B where A and B are two polynomials.
Input
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
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
题目描述:
给定两个多项式,求出两个多项式的乘积。
分析
将多项式的每一项抽象成一个包含系数和指数的项,用结构体来封装每一项;每一个多项式可以用一个结构体数组来保存。遍历两个多项式,将两个元素相乘,可以将乘积放在 map 中,这样可以自动将指数相同的项的系数相加。由于题目需要将指数大先输出,所以可以反向遍历 map 将数据取出。根据题意,如果某一项系数为 0,就应该舍去;如果所有的系数都为 0,即两个多项式的乘积为 0,这时候应该输出 0.
代码
#include <iostream>
#include <cstdio>
#include <map>
using namespace std;
struct polynomials{
int n; //指数
double an; //系数
polynomials(){}
polynomials(int x,double y){
n = x;
an = y;
}
}p1[15],p2[15],p3[105];
int main(void){
int k1,k2;
map<int,double> m;
cin>>k1;
for(int i = 0;i < k1;i++){
cin>>p1[i].n>>p1[i].an;
}
cin>>k2;
for(int i = 0;i < k2;i++){
cin>>p2[i].n>>p2[i].an;
}
for(int i = 0;i < k1;i++)
for(int j = 0;j < k2;j++){
//指数相加,系数相乘
int n = p1[i].n + p2[j].n;
double an = p1[i].an * p2[j].an;
m[n] += an;
}
int cnt = 0;
map<int,double>::reverse_iterator it;//反向迭代器
for(it = m.rbegin();it != m.rend();it++){
if(it->second != 0){ //系数不为 0
p3[cnt++] = polynomials(it->first,it->second);
}
}
if(cnt == 0){
cout<<0<<endl;
}else{
cout<<cnt<<" ";
for(int i = 0;i < cnt-1;i++)
printf("%d %.1f ",p3[i].n,p3[i].an);
printf("%d %.1f\n",p3[cnt-1].n,p3[cnt-1].an);
}
return 0;
}