题目来源:PAT (Advanced Level) Practice
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
words:
polynomial 多项式 nonzero 非零 exponent 指数 coefficient 系数
题意:
给定两个多项的每一项的指数和系数,求两个多项式相乘的结果;
思路:
1. 用两个vector<pair<int,double>>数组来存储两个多项式,first表示指数,second表示系数 ;
2. 用数组double ans[N*2]来保存相乘的结果,通过双重循环用一个多项式的每一项去乘另外一个多项式的每一项;
3. 统计相乘结果中系数非零的项的个数,并按照指数由大到小输出相乘结果的系数非零项;
//PAT ad 1009 Product of Polynomials (25 分)
#include <iostream>
using namespace std;
#include <vector>
#include <iomanip>
#include <cmath>
#define N 1005
vector <pair<int,double> > v1,v2;//用数组保存多项式,first表示指数,second表示系数
double ans[N*2]={0};
vector <double> v;
void input(vector <pair<int,double> > &v) //输入
{
int k,x;
double y;
cin>>k;
while(k--)
{
cin>>x>>y;
v.push_back({x,y});
}
}
int main()
{
int i,j,x;
double y;
input(v1); //多项式输入
input(v2);
for(i=0;i<v1.size();i++) //多项式乘法
{
for(j=0;j<v2.size();j++)
{
x=v2[j].first+v1[i].first; //指数相加
y=v2[j].second*v1[i].second; //系数相乘
ans[x] +=y;
}
}
for(i=2*N-1;i>=0;i--) //将计算得到的多项式保存到动态数组vector中便于后序输出(应为ans中有系数为0的项,这是不需要输出的)
{
if(fabs(ans[i])<0.000001) //系数为0
continue;
else
{
v.push_back(i);
v.push_back(ans[i]);
}
}
cout<<v.size()/2;
for(i=0;i<v.size();i+=2)
cout<<" "<<(int)v[i]<<" "<<fixed<<setprecision(1)<<v[i+1]; //指数以整数形式输出,系数保留一位小数
cout<<endl;
return 0;
}