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
输入样例解释:
f(A)=2.4x+3.2
f(B)=1.5x2+0.5x
- 给出两行,每行表示一个多项式,因为题意就是A+B,要求两个多项式相加
- 2(该多项式中非零项的项数)
=>接下来给出2个非零项的数据 - 1 2.4 (指数为1,系数为2.4)
- 0 3.2 (指数为0,系数为3.2,也就是常数项)
- 2(该多项式中非零项的项数)
Sample Output:
3 2 1.5 1 2.9 0 3.2
输出样例解释:
f(x)=1.5x2+2.9x+3.2
- 3(两个多项式加和之后有3项不为0的项数)
=>接下来给出2个非零项的数据 - 2 1.5 (指数为2,系数为1.5=>1.5x2)
- 1 2.9 (指数为1,系数为2.9=>2.9x)
- 0 3.2 (指数为0,系数为3.2,也就是常数项=>3.2)
#include<stdio.h>
const int max=1111;//幂次最大是1000,1000可以取到,所以p数组至少要1001,循环中不能出现i<1000
double p[max]={};//p[n]幂次为n的项的系数
int main()
{
int k,x,count=0;//k是每个多项式不为0的项数个数,x是指数,count是加和后的多项式不为0的项数个数
double a;//a是系数
//多项式f(A)输入
scanf("%d",&k);
for(int i=0;i<k;i++)
{
scanf("%d %lf",&x,&a);
p[x]=p[x]+a;//指数为x的系数和
}
//多项式f(B)输入
scanf("%d",&k);
for(int i=0;i<k;i++)
{
scanf("%d %lf",&x,&a);
p[x]=p[x]+a;//指数为x的系数和
}
//统计加和后的多项式非零项个数
for(int i=0;i<max;i++)
{
if(p[i]!=0) //因为可能存在系数一正一负加和为0的情况,所以要判断
count++;
}
//输出
printf("%d",count);//注意输出格式
for(int i=max-1;i>=0;i--)//遍历,题目要求幂次大的的先输出
{
if(p[i]!=0)
printf(" %d %.1lf",i,p[i]);//注意输出格式
}
return 0;
}