题目来源:PAT (Advanced Level) Practice 1002 A+B for 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 sum 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 to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 2 1.5 1 2.9 0 3.2
思路:
1. 将两个多项式分别保存到两个double类型的数组a和b中去,其中指数部分使用数组的下标,系数部分使用数组元素的值;
2. 使用循环对两个多项式从最高项到最低项求和(相同指数的项的系数相加),并且将相加的结果按照 指数、系数 的顺序储存到动态数组v中;
3. 按照要求输出;先输出和的项数,在从高位到低位依次输出指数和系数;
#include <iostream> //vxgzh:xtsn
using namespace std;
#include <vector>
#include <iomanip>
#include <cmath>
#define N 1005
double a[N],b[N]; //保存多项式a和b
vector <double> v;
int main()
{
int k,i,x;
double y;
cin>>k;
for(i=0;i<k;i++) //输入多项式a
{
cin>>x>>y;
a[x]=y;
}
cin>>k;
for(i=0;i<k;i++) //输入多项式b
{
cin>>x>>y;
b[x]=y;
}
for(i=N-1;i>=0;i--) //对多项式a和b进行求和,从最高项到最低项
{
y=a[i]+b[i];
if(fabs(y)<0.000001) //判断系数是否为0
continue;
else
{
v.push_back(i); //将求和的指数放入v中
v.push_back(y);//将求和的系数放入v中
}
}
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;
}